JavaScript Array Methods
Basic Array Methods
JavaScript Array length
The length
property returns the length (size) of an array:
Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let size = fruits.length;
JavaScript Array toString()
The JavaScript method toString()
converts an array to a string of (comma separated) array values.
Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.toString();
Result:
JavaScript Array at()
ES2022 intoduced the array method at()
:
Examples
Get the third element of fruits using at():
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let fruit = fruits.at(2);
Get the third element of fruits using []:
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let fruit = fruits[2];
The at()
method returns an indexed element from an array.
The at()
method returns the same as []
.
The at()
method is supported in all modern browsers since March 2022:
Chrome 92 | Edge 92 | Firefox 90 | Safari 15.4 | Opera 78 |
Apr 2021 | Jul 2021 | Jul 2021 | Mar 2022 | Aug 2021 |
Note
Many languages allows negative bracket indexing
like [-1] to access elements from the end of an object / array / string.
This is not possible in JavaScript, because [] is used for accessing both arrays and objects. obj[-1] refers to the value of key -1, not to the last property of the object.
The at()
method was introduced in ES2022 to solve this problem.
JavaScript Array join()
The join()
method also joins all array elements into a string.
It behaves just like toString()
, but in addition you can specify the separator:
Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.join(" * ");
Result:
Popping and Pushing
When you work with arrays, it is easy to remove elements and add new elements.
This is what popping and pushing is:
Popping items out of an array, or pushing items into an array.
JavaScript Array pop()
The pop()
method removes the last element from an array:
Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.pop();
The pop()
method returns the value that was "popped out":
Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let fruit = fruits.pop();
JavaScript Array push()
The push()
method adds a new element to an array (at the end):
Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Kiwi");
The push()
method returns the new array length:
Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let length = fruits.push("Kiwi");
Shifting Elements
Shifting is equivalent to popping, but working on the first element instead of the last.
JavaScript Array shift()
The shift()
method removes the first array element and "shifts" all other elements to a lower index.
Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.shift();
The shift()
method returns the value that was "shifted out":
Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let fruit = fruits.shift();
JavaScript Array unshift()
The unshift()
method adds a new element to an array (at the beginning), and "unshifts" older elements:
Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.unshift("Lemon");
The unshift()
method returns the new array length:
Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.unshift("Lemon");
Changing Elements
Array elements are accessed using their index number:
Array indexes start with 0:
[0] is the first array element
[1] is the second
[2] is the third ...
Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits[0] = "Kiwi";
JavaScript Array length
The length
property provides an easy way to append a new element to an array:
Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits[fruits.length] = "Kiwi";
JavaScript Array delete()
Warning !
Using delete()
leaves undefined
holes in the array.
Use pop() or shift() instead.
Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
delete fruits[0];
Merging Arrays (Concatenating)
In programming languages, concatenation means joining strings end-to-end.
Concatenation "snow" and "ball" gives "snowball".
Concatenating arrays means joining arrays end-to-end.
JavaScript Array concat()
The concat()
method creates a new array by merging (concatenating) existing arrays:
Example (Merging Two Arrays)
const myGirls = ["Cecilie", "Lone"];
const myBoys = ["Emil", "Tobias", "Linus"];
const myChildren = myGirls.concat(myBoys);
Note
The concat()
method does not change the existing arrays. It always returns a new array.
The concat()
method can take any number of array arguments.
Example (Merging Three Arrays)
const arr1 = ["Cecilie", "Lone"];
const arr2 = ["Emil", "Tobias", "Linus"];
const arr3 = ["Robin", "Morgan"];
const myChildren = arr1.concat(arr2, arr3);
The concat()
method can also take strings as arguments:
Example (Merging an Array with Values)
const arr1 = ["Emil", "Tobias", "Linus"];
const myChildren = arr1.concat("Peter");
Array copyWithin()
The copyWithin()
method copies array elements to another position in an array:
Examples
Copy to index 2, all elements from index 0:
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.copyWithin(2, 0);
Copy to index 2, the elements from index 0 to 2:
const fruits = ["Banana", "Orange", "Apple", "Mango", "Kiwi"];
fruits.copyWithin(2, 0, 2);
Note
The copyWithin()
method overwrites the existing values.
The copyWithin()
method does not add items to the array.
The copyWithin()
method does not change the length of the array.
Flattening an Array
Flattening an array is the process of reducing the dimensionality of an array.
Flattening is useful when you want to convert a multi-dimensional array into a one-dimensional array.
JavaScript Array flat()
ES2019 Introduced the Array flat() method.
The flat()
method creates a new array with sub-array elements concatenated to a specified depth.
Example
const myArr = [[1,2],[3,4],[5,6]];
const newArr = myArr.flat();
Browser Support
JavaScript Array flat()
is supported in all modern browsers since January 2020:
Chrome 69 | Edge 79 | Firefox 62 | Safari 12 | Opera 56 |
Sep 2018 | Jan 2020 | Sep 2018 | Sep 2018 | Sep 2018 |
JavaScript Array flatMap()
ES2019 added the Array flatMap()
method to JavaScript.
The flatMap()
method first maps all elements of an array and then creates a new array by flattening the array.
Example
const myArr = [1, 2, 3, 4, 5, 6];
const newArr = myArr.flatMap(x => [x, x * 10]);
Browser Support
JavaScript Array flatMap()
is supported in all modern browsers since January 2020:
Chrome 69 | Edge 79 | Firefox 62 | Safari 12 | Opera 56 |
Sep 2018 | Jan 2020 | Sep 2018 | Sep 2018 | Sep 2018 |
Splicing and Slicing Arrays
The splice()
method adds new items to an array.
The slice()
method slices out a piece of an array.
JavaScript Array splice()
The splice()
method can be used to add new items to an array:
Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(2, 0, "Lemon", "Kiwi");
The first parameter (2) defines the position where new elements should be added (spliced in).
The second parameter (0) defines how many elements should be removed.
The rest of the parameters ("Lemon" , "Kiwi") define the new elements to be added.
The splice()
method returns an array with the deleted items:
Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(2, 2, "Lemon", "Kiwi");
Using splice() to Remove Elements
With clever parameter setting, you can use splice()
to remove elements without leaving "holes" in the array:
Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(0, 1);
The first parameter (0) defines the position where new elements should be added (spliced in).
The second parameter (1) defines how many elements should be removed.
The rest of the parameters are omitted. No new elements will be added.
JavaScript Array toSpliced()
ES2023 added the Array toSpliced() method as a safe way to splice an array without altering the original array.
The difference between the new toSpliced() method and the old splice() method is that the new method creates a new array, keeping the original array unchanged, while the old method altered the original array.
Example
const months = ["Jan", "Feb", "Mar", "Apr"];
const spliced = months.toSpliced(0, 1);
JavaScript Array slice()
The slice()
method slices out a piece of an array into a new array:
Example
Slice out a part of an array starting from array element 1 ("Orange"):
const fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
const citrus = fruits.slice(1);
Note
The slice()
method creates a new array.
The slice()
method does not remove any elements from the source array.
Example
Slice out a part of an array starting from array element 3 ("Apple"):
const fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
const citrus = fruits.slice(3);
The slice()
method can take two arguments like slice(1, 3)
.
The method then selects elements from the start argument, and up to (but not including) the end argument.
Example
const fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
const citrus = fruits.slice(1, 3);
If the end argument is omitted, like in the first examples, the slice()
method slices out the rest of the array.
Example
const fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
const citrus = fruits.slice(2);
Automatic toString()
JavaScript automatically converts an array to a comma separated string when a primitive value is expected.
This is always the case when you try to output an array.
These two examples will produce the same result:
Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.toString();
Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits;
Note
All JavaScript objects have a toString() method.
JavaScript Array Search
Array Find and Search Methods
JavaScript Array indexOf()
The indexOf()
method searches an array for an element value and returns its position.
Note: The first item has position 0, the second item has position 1, and so on.
Example
Search an array for the item "Apple":
const fruits = ["Apple", "Orange", "Apple", "Mango"];
let position = fruits.indexOf("Apple") + 1;
Syntax
array.indexOf(item, start)
item | Required. The item to search for. |
start | Optional. Where to start the search. Negative values will start at the given position counting from the end, and search to the end. |
Array.indexOf()
returns -1 if the item is not found.
If the item is present more than once, it returns the position of the first occurrence.
JavaScript Array lastIndexOf()
Array.lastIndexOf()
is the same as Array.indexOf()
, but returns the position of the last occurrence of the specified element.
Example
Search an array for the item "Apple":
const fruits = ["Apple", "Orange", "Apple", "Mango"];
let position = fruits.lastIndexOf("Apple") + 1;
Syntax
array.lastIndexOf(item, start)
item | Required. The item to search for |
start | Optional. Where to start the search. Negative values will start at the given position counting from the end, and search to the beginning |
JavaScript Array includes()
ECMAScript 2016 introduced Array.includes()
to arrays. This allows us to check if an element is present in an array (including NaN, unlike indexOf).
Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.includes("Mango"); // is true
Syntax
array.includes(search-item)
Array.includes() allows to check for NaN values. Unlike Array.indexOf().
Browser Support
includes()
is an ECMAScript 2016 feature.
ES 2016 is fully supported in all modern browsers since March 2017:
Chrome 52 | Edge 15 | Firefox 52 | Safari 10.1 | Opera 39 |
Jul 2016 | Apr 2017 | Mar 2017 | May 2017 | Aug 2016 |
includes()
is not supported in Internet Explorer.
JavaScript Array find()
The find()
method returns the value of the first array element that passes a test function.
This example finds (returns the value of) the first element that is larger than 18:
Example
const numbers = [4, 9, 16, 25, 29];
let first = numbers.find(myFunction);
function myFunction(value, index, array) {
return value > 18;
}
Note that the function takes 3 arguments:
- The item value
- The item index
- The array itself
Browser Support
find()
is an ES6 feature (JavaScript 2015).
ES6 is fully supported in all modern browsers since June 2017:
Chrome 51 | Edge 15 | Firefox 54 | Safari 10 | Opera 38 |
May 2016 | Apr 2017 | Jun 2017 | Sep 2016 | Jun 2016 |
find()
is not supported in Internet Explorer.
JavaScript Array findIndex()
The findIndex()
method returns the index of the first array element that passes a test function.
This example finds the index of the first element that is larger than 18:
Example
const numbers = [4, 9, 16, 25, 29];
let first = numbers.findIndex(myFunction);
function myFunction(value, index, array) {
return value > 18;
}
Note that the function takes 3 arguments:
- The item value
- The item index
- The array itself
Browser Support
findIndex()
is an ES6 feature (JavaScript 2015).
ES6 is fully supported in all modern browsers since June 2017:
Chrome 51 | Edge 15 | Firefox 54 | Safari 10 | Opera 38 |
May 2016 | Apr 2017 | Jun 2017 | Sep 2016 | Jun 2016 |
findIndex()
is not supported in Internet Explorer.
JavaScript Array findLast() Method
ES2023 added the findLast() method that will start from the end of an array and return the value of the first element that satisfies a condition.
Example
const temp = [27, 28, 30, 40, 42, 35, 30];
let high = temp.findLast(x => x > 40);
Browser Support
findLast()
is an ES2023 feature.
It is supported in all modern browsers since July 2023:
Chrome 110 | Edge 110 | Firefox 115 | Safari 16.4 | Opera 96 |
Feb 2023 | Feb 2023 | Jul 2023 | Mar 2023 | May 2023 |
JavaScript Array findLastIndex() Method
The findLastIndex() method finds the index of the last element that satisfies a condition.
Example
const temp = [27, 28, 30, 40, 42, 35, 30];
let pos = temp.findLastIndex(x => x > 40);
Browser Support
findLastIndex()
is an ES2023 feature.
It is supported in all modern browsers since July 2023:
Chrome 110 | Edge 110 | Firefox 115 | Safari 16.4 | Opera 96 |
Feb 2023 | Feb 2023 | Jul 2023 | Mar 2023 | May 2023 |
JavaScript Sorting Arrays
Array Sort Methods
Sorting an Array
The sort()
method sorts an array alphabetically:
Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();
Reversing an Array
The reverse()
method reverses the elements in an array:
Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.reverse();
By combining sort()
and reverse()
, you can sort an array in descending order:
Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();
fruits.reverse();
JavaScript Array toSorted() Method
ES2023 added the toSorted()
method as a safe way to sort an array without altering the original array.
The difference between toSorted()
and sort()
is that the first method creates a new array, keeping the original array unchanged, while the last method alters the original array.
Example
const months = ["Jan", "Feb", "Mar", "Apr"];
const sorted = months.toSorted();
JavaScript Array toReversed() Method
ES2023 added the toReversed()
method as a safe way to reverse an array without altering the original array.
The difference between toReversed()
and reverse()
is that the first method creates a new array, keeping the original array unchanged, while the last method alters the original array.
Example
const months = ["Jan", "Feb", "Mar", "Apr"];
const reversed = months.toReversed();
Numeric Sort
By default, the sort()
function sorts values as strings.
This works well for strings ("Apple" comes before "Banana").
If numbers are sorted as strings, "25" is bigger than "100", because "2" is bigger than "1".
Because of this, the sort()
method will produce incorrect result when sorting numbers.
You can fix this by providing a compare function:
Example
const points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return a - b});
Use the same trick to sort an array descending:
Example
const points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return b - a});
The Compare Function
The purpose of the compare function is to define an alternative sort order.
The compare function should return a negative, zero, or positive value, depending on the arguments:
When the sort()
function compares two values, it sends the values to the compare function, and sorts the values according to the returned (negative, zero, positive) value.
If the result is negative, a
is sorted before b
.
If the result is positive, b
is sorted before a
.
If the result is 0, no changes are done with the sort order of the two values.
Example:
The compare function compares all the values in the array, two values at a time (a, b)
.
When comparing 40 and 100, the sort()
method calls the compare function(40, 100).
The function calculates 40 - 100 (a - b)
, and since the result is negative (-60), the sort function will sort 40 as a value lower than 100.
You can use this code snippet to experiment with numerically and alphabetically sorting:
<button onclick="myFunction1()">Sort Alphabetically</button>
<button onclick="myFunction2()">Sort Numerically</button>
<p id="demo"></p>
<script>
const points = [40, 100, 1, 5, 25, 10];
document.getElementById("demo").innerHTML = points;
function myFunction1() {
points.sort();
document.getElementById("demo").innerHTML = points;
}
function myFunction2() {
points.sort(function(a, b){return a - b});
document.getElementById("demo").innerHTML = points;
}
</script>
Sorting an Array in Random Order
Using a sort function, like explained above, you can sort an numeric array in random order
Example
const points = [40, 100, 1, 5, 25, 10];
points.sort(function(){return 0.5 - Math.random()});
The Fisher Yates Method
The points.sort() method in the example above is not accurate. It will favor some numbers over others.
The most popular correct method, is called the Fisher Yates shuffle, and was introduced in data science as early as 1938!
In JavaScript the method can be translated to this:
Example
const points = [40, 100, 1, 5, 25, 10];
for (let i = points.length -1; i > 0; i--) {
let j = Math.floor(Math.random() * (i+1));
let k = points[i];
points[i] = points[j];
points[j] = k;
}
Find the Lowest (or Highest) Array Value
There are no built-in functions for finding the max or min value in an array.
To find the lowest or highest value you have 3 options:
- Sort the array and read the first or last element
- Use Math.min() or Math.max()
- Write a home made function
Find Min or Max with sort()
After you have sorted an array, you can use the index to obtain the highest and lowest values.
Sort Ascending:
Example
const points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return a - b});
// now points[0] contains the lowest value
// and points[points.length-1] contains the highest value
Sort Descending:
Example
const points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return b - a});
// now points[0] contains the highest value
// and points[points.length-1] contains the lowest value
Note
Sorting a whole array is a very inefficient method if you only want to find the highest (or lowest) value.
Using Math.min() on an Array
You can use Math.min.apply
to find the lowest number in an array:
Example
function myArrayMin(arr) {
return Math.min.apply(null, arr);
}
Math.min.apply(null, [1, 2, 3])
is equivalent to Math.min(1, 2, 3)
.
Using Math.max() on an Array
You can use Math.max.apply
to find the highest number in an array:
Example
function myArrayMax(arr) {
return Math.max.apply(null, arr);
}
Math.max.apply(null, [1, 2, 3])
is equivalent to Math.max(1, 2, 3)
.
JavaScript Array Minimum Method
There is no built-in function for finding the lowest value in a JavaScript array.
The fastest code to find the lowest number is to use a home made method.
This function loops through an array comparing each value with the lowest value found:
Example (Find Min)
function myArrayMin(arr) {
let len = arr.length;
let min = Infinity;
while (len--) {
if (arr[len] < min) {
min = arr[len];
}
}
return min;
}
JavaScript Array Maximum Method
There is no built-in function for finding the highest value in a JavaScript array.
The fastest code to find the highest number is to use a home made method.
This function loops through an array comparing each value with the highest value found:
Example (Find Max)
function myArrayMax(arr) {
let len = arr.length;
let max = -Infinity;
while (len--) {
if (arr[len] > max) {
max = arr[len];
}
}
return max;
}
Sorting Object Arrays
JavaScript arrays often contain objects:
Example
const cars = [
{type:"Volvo", year:2016},
{type:"Saab", year:2001},
{type:"BMW", year:2010}
];
Even if objects have properties of different data types, the sort()
method can be used to sort the array.
The solution is to write a compare function to compare the property values:
Example
cars.sort(function(a, b){return a.year - b.year});
Comparing string properties is a little more complex:
Example
cars.sort(function(a, b){
let x = a.type.toLowerCase();
let y = b.type.toLowerCase();
if (x < y) {return -1;}
if (x > y) {return 1;}
return 0;
});
Stable Array sort()
ES2019 revised the Array sort()
method.
Before 2019, the specification allowed unstable sorting algorithms such as QuickSort.
After ES2019, browsers must use a stable sorting algorithm:
When sorting elements on a value, the elements must keep their relative position to other elements with the same value.
Example
const myArr = [
{name:"X00",price:100 },
{name:"X01",price:100 },
{name:"X02",price:100 },
{name:"X03",price:100 },
{name:"X04",price:110 },
{name:"X05",price:110 },
{name:"X06",price:110 },
{name:"X07",price:110 }
];
In the example above, when sorting on price, the result is not allowed to come out with the names in an other relative position like this:
X01 100
X03 100
X00 100
X03 100
X05 110
X04 110
X06 110
X07 110