patternjavascriptMinor
Javascript Array processing
Viewed 0 times
javascriptprocessingarray
Problem
If I have an array:
and I want to create a new array from names which afterwards will look like:
What I came up with is the following:
Seems like there should be a shorter, easier way to do this. As you can see we can repeat the names with a space n times. I'm experimenting with different ideas/concepts, having fun.
var names = ['John', 'Jim', 'Joe'];and I want to create a new array from names which afterwards will look like:
newNames = ['John John', 'Jim Jim', 'Joe Joe']What I came up with is the following:
var newNames = [];
var arr = null;
var loop = 0;
$.each(names, function (i, item) {
arr = [];
loop = 2;
while (loop--) {
arr.push(item);
}
newNames.push(arr.join(' '));
});Seems like there should be a shorter, easier way to do this. As you can see we can repeat the names with a space n times. I'm experimenting with different ideas/concepts, having fun.
Solution
You could use the native
Array.map method in modern browsers (see MDN)const newNames = ['John', 'Jim', 'Joe'].map( name => ${name} ${name});
console.log(newNames);Context
StackExchange Code Review Q#14330, answer score: 7
Revisions (0)
No revisions yet.