Most Efficient Way to Create a Zero Filled JavaScript Array

How to create a zero filled JavaScript array of arbitrary length?

How about trying like this:

Array.apply(null, new Array(10)).map(Number.prototype.valueOf,0);
//Output as [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

or

new Array(10+1).join('0').split('').map(parseFloat)
//Output as [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

EDIT:-

If your array is dynamic then simply put that in a function which takes a number and replace 10 by that variable.

Best way to create array of ten 0 in javascript

You can use a simple for loop:

var res = [];

for (var i = 1; i <= 10; i++) {
res.push(0);
}

or this:

var res = Array(10).fill(0)

create an array of zeroes of specified length javascript

//12 is an axample, the length of the arraylet arr = new Array(12).fill(0);console.log(arr)

Fastest way to set a sequential list of array items to zero

You could use Array.prototype.fill for a more "elegant" solution. It seems to be much faster as well, especially if you want to replace many indices.

const data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
const startAt = 3
const numItems = 5

data.fill(0, startAt, startAt + numItems)

console.log(data)

initialise javascript array with zeros

Testing the operation only once is very complicated, as the performance varies a lot depending on what else the computer is doing. You would have to run that single test a lot of times, and reset to the same conditions between each test. The reason that jsperf runs the test a lot of times is to get a good average to weed out the anomalies.

You should test this in different browsers, to see which method is the best overall. You will see that you get very varying results.

In Internet Explorer, the fastest methods is actually neither of the ones you tested, but a simple loop that assigns the zeroes:

for (var i = 0; i < numzeros; i++) zeros[i] = 0;

Is there any method to create an array containing consecutive zero or number type in javascript?

You could always do something like this:

const length = 10
const value = 0
const arr = Array(length).fill(value);


Related Topics



Leave a reply



Submit