Creating arrays of various sizes

Create an empty array

Use [] or Array constructor to create an empty array.

const array = [];
// []
const anotherArray = new Array();
// []

Create an array of particular length

// creates an array of length 20 but with empty elements
const array = new Array(20);
// [empty × 20]

Create an array from given values

const array = Array.of(1, 2, 3, 6, 7);
// [1, 2, 3, 6, 7]

const another = Array.of(4);
// [4]

Create an array and initialize with a value

// creates an array of length 7 with value 3
const array = Array(7).fill(3);
// [3, 3, 3, 3, 3, 3, 3]

Create an array of length N with different values

// creates an array of length 7 with values 0 to 6
const array = Array.from(Array(7).keys());
// [0, 1, 2, 3, 4, 5, 6]

// creates an array of length 7 with values 1 to 7
const anotherArray = Array.from(Array(7).keys(), (i) => i + 1);
// [1, 2, 3, 4, 5, 6, 7]

// creates an array of length 7 with even numbers
const evenArray = Array.from(Array(7).keys(), (i) => (i + 1) * 2);
// [2, 4, 6, 8, 10, 12, 14]

// creates an array of length 7 with random numbers
const randomArray = Array.from(Array(7).keys(), () => Math.random());
// [0.4629632797033538, 0.8855338574538991, 0.0065725546308867955, 0.9941066640336822, 0.6923743853921447, 0.7041447139349717, 0.5239287034447881]

Create an array from string

const string = "abcdefghi";
const array = Array.from(string);
// ["a", "b", "c", "d", "e", "f", "g", "h", "i"]

// Alternatively, you could split the string
const anotherArray = string.split("");
// ["a", "b", "c", "d", "e", "f", "g", "h", "i"]

Create an array of keys or values of an object

const person = { name: "Jack", age: "12", lang: "English" };

// array of keys of object
const personKeys = Object.keys(person);
// ["name", "age", "lang"]

// array of values of object
const personValues = Object.values(person);
// ["Jack", "12", "English"]
Last updated on Thu Jan 07 2021
Tags: