0

I have an array and I'm looking to create a new array, composed of the original array contents repeated 3 times. For example:

var array = ["red", "green", "blue"];
newArray = ["red red red", "green green green", "blue blue blue"];

My code so far:

var triples = myArray.map(function(){
  for (x = 0; x < myArray.length; x++){
    return myArray[x].repeat(3);
  };
});
console.log(triples);

But this only returns

triples = ["redredred", "redredred", "redredred"];

Any suggestions for a newbie?

2
  • 1
    return will exit that function on the first run, ex. x = 0 Commented Aug 13, 2014 at 20:39
  • String.repeat doesn't allow for inserting join characters. You'll have to do it yourself. Commented Aug 13, 2014 at 20:40

3 Answers 3

1

You can build a simple function to do this:

var triples = function(xs) {
  return xs.map(function(x) {
    return [x,x,x].join(' ')
  })
}

You can abstract it a bit more, as a transformation to use with map, and allow any number of repetitions:

var repeat = function(n) {
  return function(x) {
    return Array.apply(0, {length:n})
      .map(function(){return x})
      .join(' ')
  }
}

['foo','bar','lol'].map(repeat(3))
//^ ['foo foo foo', 'bar bar bar', 'lol lol lol']
Sign up to request clarification or add additional context in comments.

Comments

0

Here's an obnoxiously simple way of repeating all elements 3 times:

["red", "green", "blue"].map(  [].join.bind(['',' ',' ',''])   );
// == ["red red red", "green green green", "blue blue blue"]

this method also doesn't need "".repeat(), which is not universally supported yet.

another bonus: if a number, null, or other non-string sneaks in the array it won't break.

if you want it re-usable, that's easy enough:

 var repeater = [].join.bind(['',' ',' ','']) ;

 ["red", "green", "blue"].map( repeater );
 // == ["red red red", "green green green", "blue blue blue"]

 [1,2,3,4,5].map( repeater );
 // == ["1 1 1", "2 2 2", "3 3 3", "4 4 4", "5 5 5"]

Comments

0

There is no reason to use map and the loop. I guess you wanted either

var triples = myArray.map(function(str){
  return str.repeat(3);
});
console.log(triples);

or

var triples = [];
for (var x = 0; x < myArray.length; x++) {
  triples[x] = myArray[x].repeat(3);
}
console.log(triples);

However, as @digitalfresh mentioned in the comments, String::repeat doesn't insert the spaces, so you rather want to use (" "+…).repeat(3).slice(1) or use the functions presented by @dandavis or @elclanrs. Or, since you seem to use an Ecmascript 6 method anyway, you could do Array.from({length:3}, ()=>…).join(" ").

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.