Indexed Collections are collections that have numeric indices i.e. the collections of data that are ordered by an index value. This includes arrays and array-like constructs such as Array objects and TypedArray objects.
Creating an Array
1. Creating arrays without defining the array length
Syntax:
const arr2 = Array ( element0, element1, /* …, */ elementN) ;
const arr3 = [ element0, element1, /* …, */ elementN];
2. Creating an array with non-zero length, but without any items
Syntax:
// This…
const arr1 = new Array(arrayLength);
// …results in the same array as this
const arr2 = Array(arrayLength);
// This has exactly the same effect
const arr3 = [];
arr3.length = arrayLength;
Note:
In the above code,arrayLength
must be aNumber
. Otherwise, an array with a single element (the provided value) will be created. Callingarr.length
will returnarrayLength
, but the array doesn’t contain any elements. Afor...in
loop will not find any property on the array.
3. Creating an array with the given size
Syntax:
let arr = new Array(6);
let arr = Array(6);
let arr = [];
arr.length = 6;
4. Create a variable-length array and add many elements as you need
// array then add elements
let students = [];
students [0] = ‘Sujata Singh’;
students [1] = ‘Mahesh Kumar’;
students [2] = ‘Leela Nair’; // Second method: Add elements to
// an array when you create it
let fruits = [‘apple’, ‘mango’, ‘Banana’];
Accessing the Array Elements
Use indices to access array elements. Indices of Arrays are zero-based which means the index of the elements begins with zero.
1 2 3 | let fruits = ['Apple', 'Mango', 'Banana']; console.log(fruits [0]); //Apple console.log(fruits[1]); //Mango |
Understanding length
Ex:
1 2 3 | const cats = []; cats[30] = ["Dusty"]; console.log(cats.length); // 31 |
JavaScript Array indexes are 0-based: they start at 0
, not 1
. This means that the length
property will be one more than the highest index stored in the array.
You can also assign to the length
property.
Ex:
1 2 3 4 5 6 7 8 9 10 11 | const cats = ["Dusty", "Misty", "Twiggy"]; console.log(cats.length); // 3 cats.length = 2; console.log(cats); // [ 'Dusty', 'Misty' ] - Twiggy has been removed cats.length = 0; console.log(cats); // []; the cats array is empty cats.length = 3; console.log(cats); // [ <3 empty items> ] |
Iterating over Arrays
A common operation is to iterate over the values of an array, processing each one in some way. The simplest way to do this is as follows:
1 2 3 4 | const colors = ["red", "green", "blue"]; for (let i = 0; i < colors.length; i++) { console.log(colors[i]); } |
If you know that none of the elements in your array evaluate to
false
in a boolean context—if your array consists only of DOM nodes, for example—you can use a more efficient idiom:1 2 3 4 | const divs = document.getElementsByTagName("div"); for (let i = 0, div; (div = divs[i]); i++) { /* Process div in some way */ } |
The forEach() method provides another way of iterating over an array:
1 2 3 4 5 | const colors = ["red", "green", "blue"]; colors.forEach((color) => console.log(color)); // red // green // blue |
Array methods
The concat() method joins two or more arrays and returns a new array.
1 2 3 | let myArray = ["1", "2", "3"]; myArray = myArray.concat("a", "b", "c"); // myArray is now ["1", "2", "3", "a", "b", "c"] |
The join() method joins all elements of an array into a string.
1 2 | const myArray = ["Wind", "Rain", "Fire"]; const list = myArray.join(" - "); // list is "Wind - Rain - Fire" |
The push() method adds one or more elements to the end of an array and returns the resulting
length
of the array.1 2 | const myArray = ["1", "2"]; myArray.push("3"); // myArray is now ["1", "2", "3"] |
The pop() method removes the last element from an array and returns that element.
1 2 3 | const myArray = ["1", "2", "3"]; const last = myArray.pop(); // myArray is now ["1", "2"], last = "3" |
The shift() method removes the first element from an array and returns that element.
1 2 3 | const myArray = ["1", "2", "3"]; const first = myArray.shift(); // myArray is now ["2", "3"], first is "1" |
The unshift() method adds one or more elements to the front of an array and returns the new length of the array.
1 2 3 | const myArray = ["1", "2", "3"]; myArray.unshift("4", "5"); // myArray becomes ["4", "5", "1", "2", "3"] |
The slice() method extracts a section of an array and returns a new array.
1 2 3 4 | let myArray = ["a", "b", "c", "d", "e"]; myArray = myArray.slice(1, 4); // [ "b", "c", "d"] // starts at index 1 and extracts all elements // until index 3 |
The at() method returns the element at the specified index in the array, or
undefined
if the index is out of range. It’s notably used for negative indices that access elements from the end of the array.1 2 | const myArray = ["a", "b", "c", "d", "e"]; myArray.at(-2); // "d", the second-last element of myArray |
The splice() method removes elements from an array and (optionally) replaces them. It returns the items which were removed from the array.
1 2 3 4 5 6 | const myArray = ["1", "2", "3", "4", "5"]; myArray.splice(1, 3, "a", "b", "c", "d"); // myArray is now ["1", "a", "b", "c", "d", "5"] // This code started at index one (or where the "2" was), // removed 3 elements there, and then inserted all consecutive // elements in its place. |
The reverse() method transposes the elements of an array, in place: the first array element becomes the last and the last becomes the first. It returns a reference to the array.
1 2 3 | const myArray = ["1", "2", "3"]; myArray.reverse(); // transposes the array so that myArray = ["3", "2", "1"] |
The flat() method returns a new array with all sub-array elements concatenated into it recursively up to the specified depth.
1 2 3 | let myArray = [1, 2, [3, 4]]; myArray = myArray.flat(); // myArray is now [1, 2, 3, 4], since the [3, 4] subarray is flattened |
The sort() method sorts the elements of an array in place, and returns a reference to the array.
1 2 3 | const myArray = ["Wind", "Rain", "Fire"]; myArray.sort(); // sorts the array so that myArray = ["Fire", "Rain", "Wind"] |
The indexOf() method searches the array for
searchElement
and returns the index of the first match.1 2 3 4 5 6 | const a = ["a", "b", "a", "b", "a"]; console.log(a.indexOf("b")); // 1 // Now try again, starting from after the last match console.log(a.indexOf("b", 2)); // 3 console.log(a.indexOf("z")); // -1, because 'z' was not found |
The lastIndexOf() method works like
indexOf
, but starts at the end and searches backwards.1 2 3 4 5 6 | const a = ["a", "b", "c", "d", "a", "b"]; console.log(a.lastIndexOf("b")); // 5 // Now try again, starting from before the last match console.log(a.lastIndexOf("b", 4)); // 1 console.log(a.lastIndexOf("z")); // -1 |
The forEach() method executes
callback
on every array item and returns undefined
.1 2 3 4 5 6 7 8 | const a = ["a", "b", "c"]; a.forEach((element) => { console.log(element); }); // Logs: // a // b // c |
The map() method returns a new array of the return value from executing
callback
on every array item.1 2 3 | const a1 = ["a", "b", "c"]; const a2 = a1.map((item) => item.toUpperCase()); console.log(a2); // ['A', 'B', 'C'] |
The flatMap() method runs
map()
followed by a flat()
of depth 1.1 2 3 | const a1 = ["a", "b", "c"]; const a2 = a1.flatMap((item) => [item.toUpperCase(), item.toLowerCase()]); console.log(a2); // ['A', 'a', 'B', 'b', 'C', 'c'] |
The filter() method returns a new array containing the items for which
callback
returned true
.1 2 3 | const a1 = ["a", 10, "b", 20, "c", 30]; const a2 = a1.filter((item) => typeof item === "number"); console.log(a2); // [10, 20, 30] |
The find() method returns the first item.
1 2 3 | const a1 = ["a", 10, "b", 20, "c", 30]; const i = a1.find((item) => typeof item === "number"); console.log(i); // 10 |
The findLast() method returns the last item.
1 2 3 | const a1 = ["a", 10, "b", 20, "c", 30]; const i = a1.findLast((item) => typeof item === "number"); console.log(i); // 30 |
The findIndex() method returns the index of the first item.
1 2 3 | const a1 = ["a", 10, "b", 20, "c", 30]; const i = a1.findIndex((item) => typeof item === "number"); console.log(i); // 1 |
The every() method returns true
if callback
returns true
for every item in the array.
1 2 3 4 5 6 7 | function isNumber(value) { return typeof value === "number"; } const a1 = [1, 2, 3]; console.log(a1.every(isNumber)); // true const a2 = [1, "2", 3]; console.log(a2.every(isNumber)); // false |
The some() method returns true
if callback
returns true
for at least one item in the array.
1 2 3 4 5 6 7 8 9 | function isNumber(value) { return typeof value === "number"; } const a1 = [1, 2, 3]; console.log(a1.some(isNumber)); // true const a2 = [1, "2", 3]; console.log(a2.some(isNumber)); // true const a3 = ["1", "2", "3"]; console.log(a3.some(isNumber)); // false |