If I have an array:
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.
3 Answers 3
Create a function that operates on values in the manner you want...
function dupe(n) { return n + " " + n }
then use Array.prototype.map
...
var newNames = names.map(dupe)
or jQuery's not quite compliant version, $.map
...
var newNames = $.map(names, dupe)
You can also create a function factory that will make a dupe
function that will add the operate on the value a given number of times.
function dupeFactory(i) {
return function(n) {
var j = i-1
, m = n
while (j--)
m += " " + n
return m
}
}
Then use it like this...
var newNames = names.map(dupeFactory(3))
Or make reuse of the functions created from the factory, by storing them in variables...
var dupe3 = dupeFactory(3),
dupe6 = dupeFactory(6)
names.map(dupe6)
-
\$\begingroup\$ Dang, this seems to be pretty straightforward and very clean. Thanks much. \$\endgroup\$David Whitten– David Whitten2012年08月04日 12:51:11 +00:00Commented Aug 4, 2012 at 12:51
-
\$\begingroup\$ @DavidWhitten: You're welcome. I also added a solution that lets you choose how many times you want to append the name. \$\endgroup\$user10711– user107112012年08月04日 12:52:15 +00:00Commented Aug 4, 2012 at 12:52
-
\$\begingroup\$ Your
dupeFactory
does not work, it creates 2^n repetitions... \$\endgroup\$Bergi– Bergi2012年08月04日 12:53:42 +00:00Commented Aug 4, 2012 at 12:53 -
\$\begingroup\$ jsfiddle.net/6THSR \$\endgroup\$user10711– user107112012年08月04日 12:58:22 +00:00Commented Aug 4, 2012 at 12:58
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);
I guess you want to have a variable loop
value:
var names = [...];
var newNames = names.slice(0); // copy the names for the first part
for (var i=0; i<names.length; i++)
for (var j=1; j<2; j++) // sic
newNames[i] += " "+names[i];
Else, for a constantly two times a simple string concatenation will be shorter. Together with .map()
:
var newNames = names.map(function(name) {
return name+" "+name;
});
String.repeat()
. \$\endgroup\$