In javascript I need to join an array into a string with brackets. For example ['abc', 'yte', 'juu'] => (abc)(yte)(juu). I need the fastest and cleanest way to do this. I tried using the array join operator but it doesnt work on the first and last element.
You can do it with template literals. Use join() with )( separator, and wrap the result with ():
const data = ['abc', 'yte', 'juu'];
const result = `(${data.join(')(')})`;
console.log(result);
Thinking "I need the fastest and cleanest way to do this." is often not ideal. In most cases what people want is the most readable and understandable way to implement a solution.
I quite like the following. Where we first bracket each item in the array with map and then join the items with no delimiter:
const data = ['abc', 'yte', 'juu'];
let brackets = data.map(x => "(" + x + ")");
let result = brackets.join("")
console.log(result);
That of course takes two passes over the array. If you really must have the fastest solution just use a for loop:
const data = ['abc', 'yte', 'juu'];
let result = "";
for (let item of data) {
result += "(" + item + ")";
}
console.log(result);
In order to reduce an array to a single value (be that an object, array, string, number, ...) Javascript has the Array.prototype.reduce method, which achieves the desired result in a single loop and line:
console.log(['abc', 'yte', 'juu'].reduce((a,v)=>`${a}(${v})`,''))
const list = ['abc', 'yte', 'juu'];
const result = list.map(value => `(${value})`).join("");
console.log(result);
Related
For example:
str = "A=sample_text1; B=sample_text2; C=sample_text3;";
How can I get the text after "A=", which is "sample_text1" out ? (the length of sample_text1 can be very long, so str.substring won't work here)
Looks like your string has a structure where there are multiple fields where each field is represented as:
[KEY]=[VALUE];
You can use common string and array methods like split and map to extract what you need. In this case looks like you want the value of the first field:
const str = 'A=sample_text1; B=sample_text2; C=sample_text3;';
const result = str.split(';').map(s => s.split('=').pop().trim()).shift();
console.log(result); //=> 'sample_text1'
https://regexr.com is very useful for creating and testing regex.
const match = "A=sample_text1; B=sample_text2; C=sample_text3;".match(/A=([^;]*)/);
let value = match !== null ? match[1] : undefined;
Would allow you to get the value of A in this case
You could use a regular expression to capture every group surrounded by a = and a ;:
const str = "A=sample_text1; B=sample_text2; C=sample_text3;";
const regexp = "=(.*?);";
const values = [...str.matchAll(regexp)];
const aValue = values[0][1];
console.log(aValue);
It might be an overkill, but to easily access to all the keys / values, you could use Object.fromEntries:
let str = "A=sample_text1; B=sample_text2; C=sample_text3;";
let values = Object.fromEntries(
str
// Split all the pairs
.split(";")
// Remove the last empty element
.slice(0,-1)
// map to a [key, value] array to pass to Object.fromEntries
.map(i => i.split("=").map(j => j.trim())));
// get a value using a key
console.log(values["A"]) // sample_text1
// check if a key is present
console.log("C" in values) // true
console.log("D" in values) // false
It looks more longer than it is due the comments and the console logs, it can fit in one line.
Notice that this is assume of course that neither the character = or ; can be part of the key or the value.
i have this array:
array = [{"full_name":"louis jackson","title1":"english teacher,"description":"good and nice teacher"},{"full_name":"peter carey","title1":"math teacher,"description":"bad and ugly teacher"}]
i need to get this array
results = ["louis","jackson","english", "teacher",good","and","nice","teacher","peter","carey","math","teacher","bad","and","ugly","teacher"]
i have tried:
results = [];
array.forEach(item => {
results.push (item.full_name.split(" "));
results.push (item.title1.split(" "));
results.push (item.description.split(" "));
}
i just get multiple separated arrays; can anyone guide me in right way?
I made a bit of clean code to do it all for you
array = [{"full_name":"louis jackson","title1":"english teacher","description":"good and nice teacher"},{"full_name":"peter carey","title1":"math teacher","description":"bad and ugly teacher"}]
var results = array.flatMap(obj => {
const vals = Object.values(obj);
return vals.flatMap(val => val.split(' '));
})
console.log(results);
Object.values just gets the value from each property of each object, so you're not dealing with the keys like 'full_name' or 'title1'
Then once you have the values, you split them by the space and return them as an array.
flatMap makes sure that if you return an array of arrays, it flattens it 1 layer.
edit -- here's it as a one liner:
var results = array.flatMap(obj => Object.values(obj).flatMap(val => val.split(' ')));
Assuming the values are always strings and probably the words could be separated by multiple spaces:
This v.split(/ +/) splits each phrase as an array of strings which will be concatenated to the main array (the accumulator in the reduce function).
let array = [{"full_name":"louis jackson","title1":"english teacher","description":"good and nice teacher"},{"full_name":"peter carey","title1":"math teacher","description":"bad and ugly teacher"}];
let result = array.reduce((a, c) => {
Object.values(c).forEach(v => a = a.concat(v.split(/ +/)));
return a;
}, []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Your solution is close, but you just have to concat the arrays instead of pushing the split arrays into results. Like this:
let array = [{"full_name":"louis jackson","title1":"english teacher","description":"good and nice teacher"},{"full_name":"peter carey","title1":"math teacher","description":"bad and ugly teacher"}]
let results = [];
array.forEach(item => {
results = results.concat(item.full_name.split(" "))
.concat(item.title1.split(" "))
.concat(item.description.split(" "));
});
console.log(results);
Here's another take using for..of and for..in so you don't need to manually define the property names:
let array = [{"full_name":"louis jackson","title1":"english teacher","description":"good and nice teacher"},{"full_name":"peter carey","title1":"math teacher","description":"bad and ugly teacher"}]
let results = [];
for(const item of array)
for(const prop in item)
results.push(...item[prop].split(" "))
console.log(results);
result is an empty array. The split() method returns an array. When you call push() on an array, you're adding an array to an array. Every time you call push, you add another array to the array. So you have an array of arrays. What you want is a single array with all the values.
So call split() on each value to get an array, iterate through the values, then call push() on the values of the array, not the array itself.
Try this
var results = [];
array.forEach(item => {
var names = item.full_name.split(" ");
names.forEach(i => result.push(i));
var titles = item.title1.split(" ");
titles.forEach(t => result.push(t));
}
You can take #Klaycon advice and use
.concat() instead of forEach loop.
If you're not using an older version of IE you can use ... assign operator.
I am trying to make a string that lists out the dates of a month. For example, I need to make a string that lists out:
dayInDateOfBirthInput: "Day\n1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n13\n14\n15\n16\n17\n18\n19\n20\n21\n22\n23\n24\n25\n26\n27\n28\n29\n30\n31",
I've tried doing this
[Array(31).keys()].map(x => x+1).join("\n")
Thanks for looking!
I've tried doing this [Array(31).keys()].map(x => x+1).join("\n")
You are very close. .keys() returns an Array Iterator object. You need to spread it to create an array.
console.log(
[...Array(31).keys()].map(x => x+1).join("\n")
)
Your code from the comments can be tweaked:
Array(31).fill(0).map((_,x) => x+1).join("\n");
Something like
const str = 'Day' + Array(31).fill(0).map((x, i) => `\n${i+1}`).join('');
console.log(str);
As others have pointed out, your example is missing a spread operator.
Might I suggest using Array.from(...) (of which the second argument is a map function):
let result = Array.from({length:31}, (_,i) => i+1).join("\n");
console.log(result);
let resultWithDay = `Day\n${result}`;
console.log(resultWithDay);
To reverse it:
let result = Array.from({length:31}, (_,i) => i+1).reverse().join("\n");
console.log(result);
let resultWithDay = `${result}\nDay`;
console.log(resultWithDay);
i was given a homework problem to be able to create a query string based on certain parameters in an array? I am still fairly new to javascript so have some success with it but would appreciate if someone can check my code please. Thank you to everyone in advance.
I am using forEach to loop through the array to get the values and using string concatenation to get some url. I have made a sample codepen for it.
https://codepen.io/anon/pen/pmRXzg
let Person = {
name: ['Sam', 'Daisy'],
food: ['banana', 'Apple']
}
let handler = Object.entries(Person)
handler.forEach(function(element) {
console.log(element)
})
let myUrl = Object.entries(handler).map(key => key + '=' +
handler[key]).join('&')
let visitUrl = "http://someURLString/?" + myUrl
console.log(myUrl)
console.log(visitUrl)
How can i get my final result to look like
someUrlString/?name=Sam,Daisy&food=banana,apple
You can use map() on Object.entries() and then join() entries by = and then join result by &
let Person = {
name: ['Sam','Daisy'],
food: ['banana','Apple']
}
let res = Object.entries(Person).map(x=> x.join('=')).join('&');
console.log(res)
Explanation:
Object.entiries() return an array of arrays. Each array contain key value pair. In this case entries will be [['name', ['Sam','Daisy']], ['food', ['banana','Apple']]].
Now we use map() on array. map() is takes a callback. It that callback first argument(in above case its x) is current element of array through which we are iterating. map() creates new array of same length based on the value returned from callback. In above case value returned is x.join('=')
join() is method which converts array to string by adding a given substring b/w each of them. So when apply join() on
[food , ['banana','Apple']].join('=')
it will become
"food=banana,Apple"
The array ['banana','Apple'] is converted to a string implicitly. So ['banana','Apple'] is banana,Apple
In the last part we get array ["name=Sam,Daisy","food=banana,Apple"] and we join() it by &.
The point is that when we array is converted to string. It returns string in which all elements are separated by ,
You can take advantage of .entries, .map and .join to:
Map [key,value] pairs of Person.
Transform their value to a single string, by eventually manipulating data.
Join them to return the final string.
let Person = {
name: ['Sam', 'Daisy'],
food: ['banana', 'Apple']
}
const res = Object.entries(Person).map(([entryName, entryValues]) => {
return `${entryName}=${entryValues.map(i => i.toLowerCase()).join(',')}`;
}).join('&');
const url = `someUrlString/?${res}`;
console.log(url);
I am getting a set of arrays in string format which looks like
[49,16,135],[51,16,140],[50,18,150]
Now I need to save them in an array of arrays. I tried it like
let array = [];
let str = '[49,16,135],[51,16,140],[50,18,150]';
array = str.split('[]');
console.log(array);
but it is creating only one array including all string as an element while I need to have
array = [[49,16,135],[51,16,140],[50,18,150]]
Add array delimiters to each end of the string, then use JSON.parse:
const str = '[49,16,135],[51,16,140],[50,18,150]';
const json = '[' + str + ']';
const array = JSON.parse(json);
console.log(array);
You are splitting it incorrectly, in the example, it will only split of there is a [] in the string
You can create a valid JSON syntax and parse it instead like so,
let str = '[49,16,135],[51,16,140],[50,18,150]';
let array = JSON.parse(`[${str}]`);
console.log(array);
Another way you could achieve this is by using a Function constructor. This method allows you to "loosely" pass your array.
const strArr = "[49,16,135],[51,16,140],[50,18,150]",
arr = Function(`return [${strArr}]`)();
console.log(arr);