Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Push/Shift same element multiple times

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.

like image 737
Trax Avatar asked Aug 19 '17 10:08

Trax


People also ask

How do you repeat a value in JavaScript?

JavaScript String repeat() The repeat() method returns a string with a number of copies of a string. The repeat() method returns a new string. The repeat() method does not change the original string.

Is Unshift faster than push?

Unshift is slower than push because it also needs to unshift all the elements to the left once the first element is added.

What does .shift do in JavaScript?

The shift() method removes the first element from an array and returns that removed element. This method changes the length of the array.


1 Answers

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)
];
like image 56
Jonas Wilms Avatar answered Sep 26 '22 08:09

Jonas Wilms