0
\$\begingroup\$

Background

Trevor wishes to duplicate an array, transforming it by multiplying its elements four times.

Existing Solution

//
var atest =   ['a','b','c'];
var btest =   [];
btest     =   atest.concat(atest).concat(atest).concat(atest);
//
console.log(btest.length);  // btest.length == 12
console.log(btest);         // ["a", "b", "c", "a", "b", "c", "a", "b", "c", "a", "b", "c"] 

Goal

Trevor does not like this because it is ugly. Can you help Trevor find his happy place again? It's bugging Trevor.

\$\endgroup\$
5
  • 13
    \$\begingroup\$ Trevor should come here and post the question himself so he can provide some context as to why he wants to multiply the array's elements 4 times. \$\endgroup\$
    – Pimgd
    Oct 28, 2014 at 13:55
  • \$\begingroup\$ Will it always be 4, might a loop not make sense? \$\endgroup\$
    – konijn
    Oct 28, 2014 at 17:40
  • \$\begingroup\$ //why he wants to multiply the array's elements 4 times// Why not? \$\endgroup\$
    – dreftymac
    Oct 29, 2014 at 14:57
  • \$\begingroup\$ //Will it always be 4, might a loop not make sense?// A loop is fine, but something more like the way this can be done in ruby is preferred: print (['a','b','c'] * 4).inspect that gives the desired outcome \$\endgroup\$
    – dreftymac
    Oct 29, 2014 at 15:10
  • 1
    \$\begingroup\$ I am afraid that Trevor would need to write a helper function for that ;) \$\endgroup\$
    – konijn
    Oct 30, 2014 at 13:26

1 Answer 1

4
\$\begingroup\$

Here's one that uses call and manually concat a

var a = ['a','b','c'], b = Array.prototype.concat.call(a,a,a,a);

If you wanted an easy way to variably add a, just change i:

for(var a=["a","b","c"],b=[],i=4;i--;) b.push.apply(b,a);
\$\endgroup\$
0

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.