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.

1
  • 2
    Simple answer, no. Commented Aug 19, 2017 at 10:31

5 Answers 5

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)
];
Sign up to request clarification or add additional context in comments.

1 Comment

I like this solution (+1) but FYI - doesnt support IE < 12 developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
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);

Comments

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)

Comments

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);

Comments

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

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.