Javascript Push / Shift the same item multiple times

I have the following code:

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

I want to add to fooseveral times at the beginning of the array and barat the end of the array. The number of elements added should be dynamic, and the resulting array should look something like this:

['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 necessary.

+6
source share
4 answers

If better means shorter, yes, there is a way:

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

 var result = [
   ...Array(2).fill(foo),
   ...arr,
   ...Array(3).fill(bar)
];
+3
source

Try this forloopmethod. Array#unshift()added value when starting the array. pushadd with end of 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)
Run codeHide result
+1
source

unshift 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);
Hide result
0

- .

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);
Hide result
0

All Articles