JS Array Methods
Javascript -Setup
For this page, we will use two example arrays:
let numbers = [124, 322, 433, 34.2, 124214234, 234, 0.53, -142, 242, 32, 17];
let words = ["Apple", "Carrot", "Hippo", "Lemon", "Soup", "Trumpet"];
Contents
Reordering
reverse() sort() toSorted() toReversed()Finding
filter() find() findIndex() findLast() findLastIndex() indexOf() lastIndexOf()Other
concat() copyWithin() every() flat() flatMap() forEach() map() reduce() reduceRight() slice() some() splice() entries() fill() includes() join() keys() toLocaleString() toSpliced() values() with()Named indexes
This isn't an array method, but it is good to be aware of it.
Most arrays use integer indexes starting from zero:
let simpleArray = [];
simpleArray[0] = 24;
simpleArray[1] = 25;
simpleArray[3] = 26;
console.log(simpleArray); // [24,25,empty,26];
But we can instead name them:
let namedArray = [];
namedArray["A"] = 24;
namedArray["B"] = 25;
namedArray["D"] = 26;
console.log(namedArray); // [A:24,B:25,D:26];
Sort and Reverse
sort()
The method .sort() can run without any parameters:
numbers.sort(); // numbers = [-142, 0.53, 124, 124214234, 17, 234, 242, 32, 322, 34.2, 433];
words.sort(); // words = ['Apple', 'Carrot', 'Hippo', 'Lemon', 'Soup', 'Trumpet'];
Note, it modifies the original array.
sort(compareFn)
You can pass the method a function .sort(compareFn) where the function takes two array elements, let's call them (a,b)
and the function returns a number either negative, positive or zero.
| Output | Meaning |
|---|---|
| Positive | a sorted after b |
| Negative | a sorted before b |
| Zero | Original order |
let compareFn = (a,b)=>(a.toString().length - b.toString().length); // positive if a longer
numbers.sort(compareFn); // numbers = [32, 17, 124, 322, 433, 234, 242, 34.2, 0.53, -142, 124214234];
words.sort(compareFn); // words = ['Soup', 'Apple', 'Hippo', 'Lemon', 'Carrot', 'Trumpet'];
reverse()
The method .reverse() simply reverses the order of the elements:
numbers.reverse(); // numbers = [17, 32, 242, -142, 0.53, 234, 124214234, 34.2, 433, 322, 124];
words.reverse(); // words = ['Trumpet', 'Soup', 'Lemon', 'Hippo', 'Carrot', 'Apple'];
Note, it modifies the original array.
Copying counterparts
These methods all alter the array in place. If you want a new array to be created, you can use
.toSorted() and .toReversed()
Find and Filter
find()
If you want the first element of an array that matches some criteria, use find().
let numberFind = (element)=>(element < 100); // Number less than 100
let wordFind = (element)=>(element.includes("o")); // Contains letter o
numbers.find(numberFind); // 34.2
words.find(wordFind); // "Carrot"
If no results are found, it returns undefined
filter()
If you want an array of all elements of an array that matches some criteria, use filter().
numbers.filter(numberFind); // [34.2, 0.53, -142, 32, 17]
words.filter(wordFind); // ['Carrot', 'Hippo', 'Lemon', 'Soup']
If no results are found, it returns an empty array []
indexOf() and lastIndexOf()
If you want to look for the index of a specific element in an array, you can use indexOf() and lastIndexOf().
numbers.indexOf(32); // 9
words.lastIndexOf("Lemon"); // 3
If no results are found, it returns -1
Similar functions
| Method | Description |
|---|---|
.findIndex() | Returns the index of the first match 0,1,2,etc |
.findLast() | Returns the last match instead of the first |
.findLastIndex() | Returns the index of the last match 0,1,2,etc |
Other Main Methods
Here are other methods summarised:
-
concat: Combine two arrays together. Does not affect either array
let arr1 = [1,2,3]; let arr2 = [6,7,8]; arr1.concat(arr2); // [1,2,3,6,7,8] -
copyWithin: Copy elements within an array to other parts of itself.
Below example moves to position 1, elements 5 to 7. Not including a third parameter, will default to last element of arraylet arr = [1,2,3,4,5,6,7,8,9]; arr.copyWithin(1, 5, 7); // [1,6,7,4,5,6,7,8,9] -
every: Do all elements in the array pass a test? Returns boolean. Empty arrays return true
let arr = [1,2,3,4,5,6,7,8,9]; arr.every((i)=>(i>5)); // false -
some: Does some element in the array pass a test? Returns boolean. Empty arrays return true
let arr = [1,2,3,4,5,6,7,8,9]; arr.some((i)=>(i>5)); // true -
flat: Flattens an array of nested arrays. Does NOT affect original array. Can also receive parameter for level to go.
let arr = [1,2,[3,4,5],6,[7],[8,9]]; arr.flat(); // [1,2,3,4,5,6,7,8,9] -
flatMap: Applies map and then flattens. Same as .map().flat(). Does NOT affect original array.
let arr = [1,2,3,4,5]; arr.flatMap(i => [i,i*10]); // [1,10,2,20,3,30,4,40,5,50] -
forEach: Run a function for each element. Does not affect the original array
arr.forEach(x => console.log(x)); -
map: Transform each element. Does NOT affect original array.
let arr = [1,2,3]; let doubled = arr.map(x => x * 2); // [2,4,6] -
reduce: Combine all elements into a single value. Starting from the second parameter.
let arr = [1,2,3,4]; let sum = arr.reduce((acc, x) => acc + x, 0); // 10 -
reduceRight: Combine all elements into a single value from right to left. Starting from the second parameter
let arr = [1,2,3,4]; let val = arr.reduceRight((acc, x) => acc + x.toString(), "0"); // 10 -
includes: Check if an array contains a value.
arr.includes(3); // true -
join: Flattens array into a string using parameter value as separator. Does not affect original array
let arr = [1,2,3,4]; let val = arr.join(":"); // '1:2:3:4'
Other Methods
| Method | Description |
|---|---|
.slice() | Returns a new array being a section of the requested array |
.splice() | Modifies the array in place |
.toSpliced() | Same as splice() but returns a new array |
.fill() | Fills array with static value from set indicies |
.toLocaleString() | Applies toLocaleString to all elements of array and flattens into a string |
.with() | Difficult to summarise, look at details elsewhere |
.entries() | Array iterator object |
.keys() | Array iterator object |
.values() | Array iterator object |