Tell me more ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

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.

share|improve this question
Very good. Thanks much for the reply. – David Whitten Aug 4 '12 at 12:42

migrated from stackoverflow.com Aug 4 '12 at 15:55

6 Answers

up vote 2 down vote accepted

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)
share|improve this answer
Dang, this seems to be pretty straightforward and very clean. Thanks much. – David Whitten Aug 4 '12 at 12:51
@DavidWhitten: You're welcome. I also added a solution that lets you choose how many times you want to append the name. – squint Aug 4 '12 at 12:52
Your dupeFactory does not work, it creates 2^n repetitions... – Bergi Aug 4 '12 at 12:53
jsfiddle.net/6THSR – squint Aug 4 '12 at 12:58

You could use the native Array.map method in modern browsers (see MDN)

var newNames = ['John', 'Jim', 'Joe'].map(function(name){return name+' '+name});
//=> ["John John", "Jim Jim", "Joe Joe"]
share|improve this answer

You could use

var names = ['John', 'Jim', 'Joe'];
var newNames = new Array();
for (i = 0; i < names.length; i++)
      newNames.push(names[i] + ' ' + names[i]);
share|improve this answer
+1 for the use of loop syntax instead of forEach – Bergi Aug 4 '12 at 12:40
1  
Why do you consider that a better approach? – David Everlöf Aug 4 '12 at 12:41
1  
@DavidEverlöf it's clean, using less resources and above all that's the best one I know :) – yogi Aug 4 '12 at 12:42
2  
But written this way, it also creates a global variable i. And, also, this: jsperf.com/literal-vs-constructor-array/4 – Ivan Vergiliev Aug 4 '12 at 12:44
@IvanVergiliev: See my answer for a better version – Bergi Aug 4 '12 at 12:51
var newNames = [];
$.each(names, function(i, item) {
  newNames.push(item + ' ' + item);
})
share|improve this answer

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;
});
share|improve this answer

I've been doing som ereading, and I've found a really elegant solution that I wanted to share. Here it is:

var names = [ 'John', 'Jim', 'Joe' ];

var newNames = $.map(names, function (n) {
    var repeats = 3;
    return $.trim((new Array(repeats + 1).join(' ' + n)));
});

In this case I want to repeat the names three(3) times. I add an extra repeat to ensure that the last element is covered.

The responses from everyone was really cool.

Thanks again

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.