Most efficient way to create a zero filled JavaScript array?

前端 未结 30 1188
花落未央
花落未央 2020-11-22 05:58

What is the most efficient way to create an arbitrary length zero filled array in JavaScript?

相关标签:
30条回答
  • 2020-11-22 06:02

    ES6 solution:

    [...new Array(5)].map(x => 0); // [0, 0, 0, 0, 0]
    
    0 讨论(0)
  • 2020-11-22 06:04

    Elegant way to fill an array with precomputed values

    Here is another way to do it using ES6 that nobody has mentioned so far:

    > Array.from(Array(3), () => 0)
    < [0, 0, 0]
    

    It works by passing a map function as the second parameter of Array.from.

    In the example above, the first parameter allocates an array of 3 positions filled with the value undefined and then the lambda function maps each one of them to the value 0.

    Although Array(len).fill(0) is shorter, it doesn't work if you need to fill the array by doing some computation first (I know the question didn't ask for it, but a lot of people end up here looking for this).

    For instance, if you need an array with 10 random numbers:

    > Array.from(Array(10), () => Math.floor(10 * Math.random()))
    < [3, 6, 8, 1, 9, 3, 0, 6, 7, 1]
    

    It's more concise (and elegant) than the equivalent:

    const numbers = Array(10);
    for (let i = 0; i < numbers.length; i++) {
        numbers[i] = Math.round(10 * Math.random());
    }
    

    This method can also be used to generate sequences of numbers by taking advantage of the index parameter provided in the callback:

    > Array.from(Array(10), (d, i) => i)
    < [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    

    Bonus answer: fill an array using String repeat()

    Since this answer is getting a good deal of attention, I also wanted to show this cool trick. Although not as useful as my main answer, will introduce the still not very known, but very useful String repeat() method. Here's the trick:

    > "?".repeat(10).split("").map(() => Math.floor(10 * Math.random()))
    < [5, 6, 3, 5, 0, 8, 2, 7, 4, 1]
    

    Cool, huh? repeat() is a very useful method to create a string that is the repetition of the original string a certain number of times. After that, split() creates an array for us, which is then map()ped to the values we want. Breaking it down in steps:

    > "?".repeat(10)
    < "??????????"
    
    > "?".repeat(10).split("")
    < ["?", "?", "?", "?", "?", "?", "?", "?", "?", "?"]
    
    > "?".repeat(10).split("").map(() => Math.floor(10 * Math.random()))
    < [5, 6, 3, 5, 0, 8, 2, 7, 4, 1]
    
    0 讨论(0)
  • 2020-11-22 06:04

    If you need to create many zero filled arrays of different lengths during the execution of your code, the fastest way I've found to achieve this is to create a zero array once, using one of the methods mentioned on this topic, of a length which you know will never be exceeded, and then slice that array as necessary.

    For example (using the function from the chosen answer above to initialize the array), create a zero filled array of length maxLength, as a variable visible to the code that needs zero arrays:

    var zero = newFilledArray(maxLength, 0);
    

    Now slice this array everytime you need a zero filled array of length requiredLength < maxLength:

    zero.slice(0, requiredLength);
    

    I was creating zero filled arrays thousands of times during execution of my code, this speeded up the process tremendously.

    0 讨论(0)
  • 2020-11-22 06:04

    To create an all new Array

    new Array(arrayLength).fill(0);
    

    To add some values at the end of an existing Array

    [...existingArray, ...new Array(numberOfElementsToAdd).fill(0)]

    Example

    //**To create an all new Array**
    
    console.log(new Array(5).fill(0));
    
    //**To add some values at the end of an existing Array**
    
    let existingArray = [1,2,3]
    
    console.log([...existingArray, ...new Array(5).fill(0)]);

    0 讨论(0)
  • 2020-11-22 06:05

    The already mentioned ES 6 fill method takes care of this nicely. Most modern desktop browsers already support the required Array prototype methods as of today (Chromium, FF, Edge and Safari) [1]. You can look up details on MDN. A simple usage example is

    a = new Array(10).fill(0);
    

    Given the current browser support you should be cautious to use this unless you are sure your audience uses modern Desktop browsers.

    0 讨论(0)
  • 2020-11-22 06:06

    Although this is an old thread, I wanted to add my 2 cents to it. Not sure how slow/fast this is, but it's a quick one liner. Here is what I do:

    If I want to pre-fill with a number:

    Array.apply(null, Array(5)).map(Number.prototype.valueOf,0);
    // [0, 0, 0, 0, 0]
    

    If I want to pre-fill with a string:

    Array.apply(null, Array(3)).map(String.prototype.valueOf,"hi")
    // ["hi", "hi", "hi"]
    

    Other answers have suggested:

    new Array(5+1).join('0').split('')
    // ["0", "0", "0", "0", "0"]
    

    but if you want 0 (the number) and not "0" (zero inside a string), you can do:

    new Array(5+1).join('0').split('').map(parseFloat)
    // [0, 0, 0, 0, 0]
    
    0 讨论(0)
提交回复
热议问题