I imagine this is similar to array padding, but I wonder if it can be simplified at all.
var arr = [1,2,3],
x = 5;
for (var i=0; i<x; i++) {
arr.push(x);
}
console.log(arr);
//=> [1, 2, 3, 5, 5, 5, 5, 5]
Is there any way to do this without using the for loop?
Update
Even though there are more clever solutions, the for loop seems to be the most performant.
Benchmarks on jsperf
I imagine this is similar to array padding, but I wonder if it can be simplified at all.
var arr = [1,2,3],
x = 5;
for (var i=0; i<x; i++) {
arr.push(x);
}
console.log(arr);
//=> [1, 2, 3, 5, 5, 5, 5, 5]
Is there any way to do this without using the for loop?
Update
Even though there are more clever solutions, the for loop seems to be the most performant.
Benchmarks on jsperf
Share Improve this question edited Jun 3, 2024 at 15:19 Kylok 7696 silver badges16 bronze badges asked Mar 19, 2014 at 1:42 MulanMulan 135k34 gold badges238 silver badges274 bronze badges 04 Answers
Reset to default 14Unless you get penalised for each line of code you write, that code is fine: succinct and very understandable.
If you do get penalised, just use:
for (var i = 0; i < x; i++) arr.push(x);
on a single line :-)
Beyond that, your best bet would be a function along the lines of:
arr = appendXCopiesOfX (arr, x);
but I don't think you're really gaining anything there since, as mentioned, there should be very little problem understanding such a small loop.
All in all, it's probably a waste of time and effort trying to improve what you currently have.
Without for loop:
var arr = [1,2,3], x = 5;
arr = arr.concat(Array.apply(null, Array(x)).map(function() { return x; }));
// or even
arr = arr.concat(Array.apply(null, Array(x)).map(x.valueOf, x));
For those using ES6 and have e across this issue. Try using Array.fill() https://developer.mozilla/en/docs/Web/JavaScript/Reference/Global_Objects/Array/fill
I used this method in testing to generate mock data for x rows without needing to loop.
Edit: Sorry, I was off on this one. This code will generate an array x long, but they would all have the same value. A better code snippet is at the end of this post.
newOrdersX: function(x) {
return Array(x).fill({
name: faker.random.name()
});
}`
This one will be an array x levels long, but each value will be different. Note that .fill()
still needs to be called or it won't work.
newOrdersX: function(x) {
return Array(x).fill().map(() => ({
name: faker.random.name()
}));
}`
Another ES6 option is to use Array.from()
to create an array with the length of the original array + x
:
const pad = (arr, x) =>
Array.from({ length: arr.length + x }, (_, i) => arr[i] ?? x)
const arr = [1,2,3], x = 5;
console.log(pad(arr, x));