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.
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.
Unshift is slower than push because it also needs to unshift all the elements to the left once the first element is added.
The shift() method removes the first element from an array and returns that removed element. This method changes the length of the array.
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)
];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With