Sunday, June 2, 2024
 Popular · Latest · Hot · Upcoming
15
rated 0 times [  19] [ 4]  / answers: 1 / hits: 18490  / 10 Years ago, wed, march 19, 2014, 12:00:00

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's mover clever solutions, the for-loop seems to be the most performant


array-fill-2 Benchmarks on jsperf


More From » arrays

 Answers
28

Unless 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.


[#71914] Monday, March 17, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
serena

Total Points: 488
Total Questions: 125
Total Answers: 114

Location: Estonia
Member since Wed, Jun 8, 2022
2 Years ago
;