[Solved] – JavaScript – How can we create most efficient way to create a zero filled JavaScript array?

How can we create most efficient way to create a zero filled JavaScript array?

Asked on October 20, 2018 in Javascript.
Add Comment


  • 3 Answer(s)

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

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

    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.

    Answered on October 20, 2018.
    Add Comment

    With most languages, it would be pre-allocate, then zero-fill

    function newFilledArray(len, val) {
        var rv = new Array(len);
        while (--len >= 0) {
            rv[len] = val;
        }
        return rv;
    }
    

    But, JavaScript arrays aren’t really arrays, they’re key/value maps just like all other JavaScript objects, so there’s no “pre-allocate” to do . By using the above code it is possible to create a zero filled javascript array

    Answered on October 20, 2018.
    Add Comment

    It is to create the array of the 10 number with random numbers

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

    First a numbers variable is defined as const and with the value of the array contains of 10 numbers
    and the for loop is used with number.length and increment is made till 10 and it is stored in array math function
    is used up with rounds of 10 and the values get randomized.

    Answered on October 20, 2018.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.