9

I have the following code:

var foo = 'foo'
var bar = 'bar'
var arr = [1,2,3]

I want to add to foo several times at the beginning of the array and bar at the end of the array. The number of times each element added should be dynamic and the resulting array should be something like:

['foo','foo',1,2,3,'bar',bar','bar']

Is there a better method than using a loop for each element?I could use lodash if needed.

Trax
  • 1,445
  • 5
  • 19
  • 39

5 Answers5

16

If better means shorter, yes there's a way:

 var foo = 'foo';
 var bar = 'bar' 
 var arr = [1,2,3]

 var result = [
   ...Array(2).fill(foo),
   ...arr,
   ...Array(3).fill(bar)
];
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
  • I like this solution (+1) but FYI - doesnt support IE < 12 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/fill – Rahul Desai Nov 08 '19 at 20:12
2

Or something like this.

var foo = Array.from({length:2}, v => 'foo');
var bar = Array.from({length:3}, v => 'bar');
var arr = [1,2,3]

arr.push(...bar);
arr.unshift(...foo);
console.log(arr);
keja
  • 1,333
  • 1
  • 14
  • 21
1

Try this forloop method. Array#unshift() added the value on starting of array.push add with end of the array

var foo = 'foo'
var bar = 'bar'
var arr = [1,2,3]

for(var i=0; i<(Math.random() * 5); i++){
arr.unshift(foo)
}
for(var i=0; i<(Math.random() * 5); i++){
arr.push(bar)
}
console.log(arr)
prasanth
  • 22,145
  • 4
  • 29
  • 53
0

You can use unshift and push like

function pushToBeginning(arr, str, count){
    while(count--){
        arr.unshift(str);
    }
}

function pushToEnd(arr, str, count){
    while(count--){
        arr.push(str);
    }
}

let arr = [1, 2, 3];

pushToBeginning(arr, 'Foo', 3);
pushToEnd(arr, 'Bar', 2);

console.log(arr);
marvel308
  • 10,288
  • 1
  • 21
  • 32
0

most of the answers here use spread syntax or for loops to push. But its recommended to use Array.concat() for better performance & to avoid stack overflow error:

var foo = 'foo';
var bar = 'bar'
var arr = [1, 2, 3]

var result = arr.concat(Array(2).fill(foo), Array(3).fill(bar));
console.log(result)

Note that - according to this answer Array.fill is only recommended for primitive data types.

for non-primitives, you need to use Array.from because then all elements in the array will reference the same object in memory, so mutations to one item in the array will affect every item in the array

Gangula
  • 5,193
  • 4
  • 30
  • 59