Create array javascript with length

[...Array(6)].map(x => 0);
// [0, 0, 0, 0, 0, 0]

OR

Array(6).fill(0);
// [0, 0, 0, 0, 0, 0]

Note: you can't loop empty slots i.e. Array(4).forEach(() => …)


OR

( typescript safe )

Array(6).fill(null).map((_, i) => i);
// [0, 1, 2, 3, 4, 5]

OR

Classic method using a function ( works in any browser )

function NewArray(size) {
    var x = [];
    for (var i = 0; i < size; ++i) {
        x[i] = i;
    }
    return x;
}

var a = NewArray(10);
// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Creating nested arrays

When creating a 2D array with the fill intuitively should create new instances. But what actually going to happen is the same array will be stored as a reference.

var a = Array(3).fill([6]);
// [  [6], [6], [6]  ]

a[0].push(9);
// [  [6, 9], [6, 9], [6, 9]  ]

Solution

var a = [...Array(3)].map(x => []);

a[0].push(4, 2);
// [  [4, 2], [], []  ]

So a 3x2 Array will look something like this:

[...Array(3)].map(x => Array(2).fill(0));
// [  [0, 0], [0, 0], [0, 0]  ]

N-dimensional array

function NArray(...dimensions) {
    var index = 0;
    function NArrayRec(dims) {
        var first = dims[0], next = dims.slice().splice(1); 
        if(dims.length > 1) 
            return Array(dims[0]).fill(null).map((x, i) => NArrayRec(next ));
        return Array(dims[0]).fill(null).map((x, i) => (index++));
    }
    return NArrayRec(dimensions);
}

var arr = NArray(3, 2, 4);
// [   [  [ 0,  1,  2,  3 ] , [  4,  5,  6,  7]  ],
//     [  [ 8,  9,  10, 11] , [ 12, 13, 14, 15]  ],
//     [  [ 16, 17, 18, 19] , [ 20, 21, 22, 23]  ]   ]

Initialize a chessboard

var Chessboard = [...Array(8)].map((x, j) => {
    return Array(8).fill(null).map((y, i) => {
        return `${String.fromCharCode(65 + i)}${8 - j}`;
    });
});

// [ [A8, B8, C8, D8, E8, F8, G8, H8],
//   [A7, B7, C7, D7, E7, F7, G7, H7],
//   [A6, B6, C6, D6, E6, F6, G6, H6],
//   [A5, B5, C5, D5, E5, F5, G5, H5],
//   [A4, B4, C4, D4, E4, F4, G4, H4],
//   [A3, B3, C3, D3, E3, F3, G3, H3],
//   [A2, B2, C2, D2, E2, F2, G2, H2],
//   [A1, B1, C1, D1, E1, F1, G1, H1] ]

Math filled values

handy little method overload when working with math


function NewArray( size , method, linear )
{
    method = method || ( i => i ); 
    linear = linear || false;
    var x = [];
    for( var i = 0; i < size; ++i )
        x[ i ] = method( linear ? i / (size-1) : i );
    return x;
}

NewArray( 4 ); 
// [ 0, 1, 2, 3 ]

NewArray( 4, Math.sin ); 
// [ 0, 0.841, 0.909, 0.141 ]

NewArray( 4, Math.sin, true );
// [ 0, 0.327, 0.618, 0.841 ]

var pow2 = ( x ) => x * x;

NewArray( 4, pow2 ); 
// [ 0, 1, 4, 9 ]

NewArray( 4, pow2, true ); 
// [ 0, 0.111, 0.444, 1 ]

  1. HowTo
  2. JavaScript Howtos
  3. Create Array of Specific Length in JavaScript

Created: October-17, 2021 | Updated: January-22, 2022

  1. Create an Array of Length Using Array() Constructor in JavaScript
  2. Create an Array of Lengths Using the apply() Method in JavaScript
  3. Create an Array of Lengths Using the map() Method in JavaScript
  4. Creates an Array of Length Using the fill() Method in JavaScript

In JavaScript, you might need to create or declare an array of specific lengths and insert values you want inside the array. It can be achieved using different ways.

Below are some of the most ways to create an array of specific lengths in JavaScript. Now only use this in case you think there is a need for this because most of the time, there is no need to create or declare an array of specific lengths; you can dynamically make an array and use it.

Create an Array of Length Using Array() Constructor in JavaScript

The first way of creating an empty array of specific lengths is by using the Array() constructor and passing an integer as an argument to it. Since we are calling a constructor, we will be using the new keyword.

var arr = new Array(5);
console.log(arr)

Output:

[undefined, undefined, undefined, undefined, undefined]

This way of creating an array of specific lengths is not recommended if you are using JSlint, as it might cause issues. Since this way is ambiguous and it does not just create an array of a particular length, it can also be used to do other things like creating an array containing a value as follows.

var arr_2 = new Array('5');
console.log(arr_2)

Output:

[ "5" ]

Create an Array of Lengths Using the apply() Method in JavaScript

The Array constructor provides a method called apply(). Using this apply() method, you can provide arguments to a method in the form of an array. The apply() method takes two arguments, the first is the reference to this argument, and the second is the array.

var myArr = Array.apply(null, Array(5));
console.log(myArr);

Output:

[undefined, undefined, undefined, undefined, undefined]

To create an empty array of a specific length, let’s say 5, we will pass null as the first argument, and the second is the array Array(5). This will create an array of length 5 and initialize each element with an undefined value.

Alternatively, you can also do the following. Here, you can pass an array object as the second parameter and then inside it define the length of the array that you want to create, in this case, 5.

var arr = Array.apply( null, { length: 5 } );
console.log(arr);
console.log(arr.length);

Output:

[undefined, undefined, undefined, undefined, undefined]
5

Create an Array of Lengths Using the map() Method in JavaScript

Another way of creating an array of specific lengths is to use the map() method in JavaScript. Here, the Array(5) constructor will create an empty array of length 5. This is similar to what we saw previously. Then using the spread operator ..., we will spread every element of the array and enclose this inside a square bracket like this [...Array(5)]. It will create an array of length 5 where the value of each element will be undefine. Then to initialize this array, we will make use of the map() method.

[...Array(5)].map(x => 0);

Output:

[0, 0, 0, 0, 0]

Using the map() method, we will take every element inside the x variable and then add value zero to it. This will initialize all the elements of the array to zero.

Creates an Array of Length Using the fill() Method in JavaScript

The fill() method also works the same way as map() does; the only thing is that the fill() does not take any function as a parameter. It directly takes a value as an input. You can create an array of specific length Array(5) and then fill the array with some integer value, as shown below.

Array(5).fill(0);
// [0, 0, 0, 0, 0]

Write for us

DelftStack articles are written by software geeks like you. If you also would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - JavaScript Array

  • Check if Array Contains Value in JavaScript
  • Convert Array to String in JavaScript
  • Remove First Element From an Array in JavaScript
  • Create array javascript with length

    Does array have length method?

    Unlike the String and ArrayList, Java arrays do not have a size() or length() method, only a length property.

    How do you create an array of given lengths?

    One common way of creating an Array with a given length, is to use the Array constructor: const LEN = 3; const arr = new Array(LEN); assert. equal(arr. length, LEN); // arr only has holes in it assert.

    How do you create an array of 5 elements?

    “create an array with 5 elements js” Code Answer's.
    function range(start, end) {.
    return Array(end - start + 1). fill(). map((_, idx) => start + idx).
    var result = range(9, 18); // [9, 10, 11, 12, 13, 14, 15, 16, 17, 18].
    console. log(result);.

    How does array length work in JavaScript?

    What exactly is the JavaScript Array length property. By definition, the length property of an array is an unsigned, 32-bit integer that is always numerically greater than the highest index in the array. The value of the length is 232. It means that an array can hold up to 4294967296 (232) elements.