Array methods in JavaScript

Working examples of 34 JavaScript array methods.

another bored fish

A to Z of string methods

atincludesslice
concatindexOfsplice
copyWithinjoinsome
everylastIndexOfsort
fillmaptoReversed
filterpoptoSorted
findpushtoSpliced
findIndexreducetoString
findLastreduceRightunshift
findLastIndexreversevalues
flatshiftwith
forEach

↑ A to Z of methods

at

Similar to the array bracket notation the at method identifies the value at the given index. However the bracket notation does not work backwards from the end of the array whereas the at method does.

const farm = ['cow', 'chicken', 'pig', 'goat']

console.log(farm.at(0) === farm[0])  // true
console.log(farm.at(0)) // cow
console.log(farm[-1]) // undefined
console.log(farm.at(-1)) // goat
console.log(farm.at(-2)) // pig

↑ A to Z of methods

concat

The concat method creates a new array with merged array, without changing the original arrays.

const letters_1 = ['a', 'b', 'c']
const letters_2 = ['x', 'y', 'z']

const merged = letters_1.concat(letters_2)

console.log(merged) // ['a', 'b', 'c', 'x', 'y', 'z']

The ES6 spread operator achieves the same effect and, in my view, is cleaner and more understandable.

const spreaded = [...letters_1, ...letters_2]

console.log(spreaded) // ['a', 'b', 'c', 'x', 'y', 'z']

↑ A to Z of methods

copyWithin

This might blow your mind. I cannot think of a use case for the copyWithin method. I have never used it but include it here because it exists.

The copyWithin method copies elements to another location within the array without changing its length. The syntax is as follows:

copyWithin(target, start)

or

copyWithin(target, start, end)

const colours_1 = ['πŸ”΄', '🟒', 'πŸ”΅', '🟑']

const copyBlueYellow = colours_1.copyWithin(0, 2, 4)

console.log(copyBlueYellow) 
// ['πŸ”΅', '🟑', 'πŸ”΅', '🟑']
const colours_2 = ['πŸ”΄', '🟒', 'πŸ”΅', '🟑']

const copyRedGreen = colours_2.copyWithin(2, 0, 3)

console.log(copyRedGreen) 
// ['πŸ”΄', '🟒', 'πŸ”΄', '🟒']
const colours_3 = ['πŸ”΄', '🟒', 'πŸ”΅', '🟑']

const copyFromGreen = colours_3.copyWithin(0, 1)

console.log(copyFromGreen) 
// ['🟒', 'πŸ”΅', '🟑', '🟑']

Notice in the last example in which the end of the copy wasn’t stated, the copy started at index 1 and also copied indexes 2 and 3. The array length did not change.


↑ A to Z of methods

every

The every method returns a boolean based on all values in the array meeting a given condition. Let’s take a look.

const ages_1 = [45, 22, 17, 37, 26]
const ages_2 = [45, 22, 20, 37, 26]

const adult = age => age > 18;

console.log(ages_1.every(adult)) // false

console.log(ages_2.every(adult)) // true

↑ A to Z of methods

fill

The fill method fills an array with a given value. The syntax is as follows:

arr.fill(value, start, end)

const original = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

console.log(original.fill(0, 9))
// [0, 1, 2, 3, 4, 5, 6, 7, 8, 0]

console.log(original.fill(0, 5, 9))
// [0, 1, 2, 3, 4, 0, 0, 0, 0, 0]

console.log(original.fill(0))
// [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

↑ A to Z of methods

filter

The filter method creates an array of elements that match a condition, all other elements are filtered out.

const countdown = [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

const middleNums = n => n < 7 && n > 3;

console.log(countdown.filter(middleNums))
// [6, 5, 4]

Here we create an array called middleNums and filter the countdown array above for numbers that at greater than 3 but less than 7. You can see that the other numbers do not appear in the new array.

const tasks = [
 { name: 'Learn JavaScript', done: false },
 { name: 'Grocery shopping', done: false },
 { name: 'Cook breakfast', done: true }
]

const completedTasks = tasks.filter(el => el.done)

console.log(completedTasks)
// [{name: 'Cook breakfast', done: true}}]

Here the completedTasks array filters the tasks array for elements marked done: true.


↑ A to Z of methods

find

The find method returns the first value that matches a given condition.

const countdown = [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
const nearZero = n => n < 3;

console.log(countdown.find(nearZero))
// 2

In other words the first value less than 3 in the array is the value of 2.


↑ A to Z of methods

findIndex

The findIndex method returns the first index that matches a given condition.

const countdown = [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
const nearZero = n => n < 3;

console.log(countdown.findIndex(nearZero))
// 7

In other words the first value less than 3 in the array is found at index 7, or countdown[7].


↑ A to Z of methods

findLast

The findLast method returns the last value that matches a given condition.

const game = [2, 1, 4, 16, 32]

console.log(game.findLast(n => n > 15))
// 16

In other words the last value greater than 15 in the array is the value of 16.


↑ A to Z of methods

findLastIndex

The findLastIndex method returns the last index that matches a given condition.

const game = [2, 1, 4, 16, 32]

console.log(game.findLastIndex(n => n > 15))
// 3

In other words the last value greater than 15 in the array is found at index 3, or game[3].


↑ A to Z of methods

flat

The flat method flattens a shallow nested array into a single array.

const nested = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

console.log(nested.flat())
// [1, 2, 3, 4, 5, 6, 7, 8, 9]

↑ A to Z of methods

forEach

The forEach loops, or iterates, over each element of the array and performs the given function.

const nested = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
const odds = []

nested.flat().forEach(n => {
  if (n % 2 !== 0) {
    odds.push(n)
  }
})

console.log(odds)
// [1, 3, 5, 7, 9]

In other words the previous nested is flattened as above, then iterated over. If an element is not even the value will be pushed into the array called odds.


↑ A to Z of methods

includes

The includes method returns a boolean based upon the given condition.

const code = ['HTML', 'CSS', 'JavaScript', , null, NaN]

console.log(code.includes('HTML')) // true
console.log(code.includes(undefined)) // true
console.log(code.includes(null)) // true
console.log(code.includes(NaN)) // true

We can see that the includes() method also recognises null, undefined and NaN as values.

console.log(code.includes('Svelte')) // false
console.log(!code.includes('Svelte')) // true

Note that we can also check for not included by using the exclamation mark ! before the array name.


↑ A to Z of methods

indexOf

The indexOf method returns the first index that matches a given condition. The method can take one or 2 arguments. Here is the syntax for each:

arr.indexOf(value)

arr.indexOf(value, from)

Let’s have a look.

const upDown = [1, 2, 3, 4, 5, 4, 3, 2, 1]

console.log(upDown.indexOf(3))
// 2

The first array index with the value 3 is 2, or upDown[2].

console.log(upDown.indexOf(3, 4))
// 6

The first element with the value 3 after index 4, or upDown[4], is at index 6, or upDown[6].


↑ A to Z of methods

join

The join() method allows us to create a string from array elements. Be careful what you wish for because the results might be a bit weird.

const words = ['Always', 'loving', 'JavaScript']

console.log(words.join())
// Always,loving,JavaScript

console.log(words.join(''))
//AlwayslovingJavaScript

console.log(words.join(' '))
//Always loving JavaScript

console.log(words.join(' .. '))
// Always .. loving .. JavaScript

↑ A to Z of methods

lastIndexOf

The lastIndexOf is similar to the indexOf methods, but it loops the array from the end. The syntax is as follows:

arr.lastIndexOf(value)

arr.lastIndexOf(value, from)

Let’s have a look.

const downUp = [5, 4, 3, 2, 1, 2, 3, 4, 5]

console.log(downUp.lastIndexOf(4))
// 7

The last array index of the value 4 is 7, or downUp[7].

console.log(downUp.lastIndexOf(4, 4))
// 1

The last index of the value 4 but starting from downUp[4] is 1.


↑ A to Z of methods

map

The map method iterates, or loops, over the array to return a new array based on the function passed in.

const nums = [2, 4, 6, 8, 10]
const doubled = nums.map(n => n * 2)

console.log(doubled)
// [4, 8, 12, 16, 20]

The map method does not change the original array. It creates an array based on the function within. In this case, each array element is multipled by 2.


↑ A to Z of methods

pop

The pop method removes the last element from an array. Using the nums array above, it looks like this:

const nums = [2, 4, 6, 8, 10]
nums.pop()

console.log(nums)
// [2, 4, 6, 8]

↑ A to Z of methods

push

The push() method adds its value to the end of an array. Using the nums array above, it looks like this:

const nums = [2, 4, 6, 8, 10]
nums.push(24)

console.log(nums)
// [2, 4, 6, 8, 24]

↑ A to Z of methods

reduce

The reduce method calculates the looped values in turn to create a single value based on the internal function. In other words, it reduces the array to a single value.

I have previously written that the awesome MDN Docs names the first argument as accumulator and the second argument as currentValue. I liked Jonas Schmedtmann’s description of the first argument being like a snowball that rolls through the array getting bigger as it goes.

Let’s take a look.

const addThese = [11, 100, 1100]
const added = addThese.reduce((snowball, currentValue) => snowball + currentValue);

console.log(added)
// 1211

Using the snowball analogy to explain what is going on, at the first element (11) the snowball is zero. Eleven is added to the snowball (now 11) and the next currentValue is 100. That gets added to the snowbal (now 111) .. and so on through the array until the end.

We can also multiply elements using the reduce method.

const multiplyThese = [12, 14, 16]
const multiplied = multiplyThese.reduce((snowball, currentValue) => snowball * currentValue);

console.log(multiplied)
// 2688

↑ A to Z of methods

reduceRight

The reduceRight does the same thing as reduce but starts with the snowball at the end of the array and works backwards.


↑ A to Z of methods

reverse

The reverse method does exactly what is says on the tin. It reverses all the index values in the array.

const reverseThese = ['JavaScript', 'love', 'really', 'We'];

console.log(reverseThese.reverse())
// ['We', 'really', 'love', 'JavaScript']

↑ A to Z of methods

shift

The shift method simply removes the first element from the array.

const users = ['Mary', 'Erin', 'George', 'Claire']
users.shift()

console.log(users)
// ['Erin', 'George', 'Claire']

↑ A to Z of methods

slice

The slice method creates a new array based on elements sliced (or copied) from another array. It does not affect the original array. The syntax is like this:

array.slice(fromHere, toHereButDoNotInclude)

const moreUsers = ['Mary', 'Erin', 'George', 'Claire', 'Mike', 'Bob']

const copiedUsers = moreUsers.slice(2, 4)

console.log(copiedUsers)
// ['George', 'Claire']

The slice above started at moreUsers[2] (β€˜George’) and stopped at but did not include moreUsers[4] (β€˜Mike’)


↑ A to Z of methods

splice

The .splice method does affect the array that is spliced. We can remove and replace elements from the middle of an array. The syntax is as follows:

array.splice(start)

array.splice(start, end)

array.splice(start, end, replace)

const folk = ['Bob', 'Mike', 'Sue', 'Helen', 'Scott']
folk.splice(2)

console.log(folk)
// ['Bob', 'Mike']

The splice started at folk[1] and removed the rest of the elements in the array.

const folk = ['Bob', 'Mike', 'Sue', 'Helen', 'Scott']
folk.splice(2, 1)

console.log(folk)
// ['Bob', 'Mike', 'Helen', 'Scott']

The splice started at folk[2] and removed one element (β€˜Sue’).

const folk = ['Bob', 'Mike', 'Sue', 'Helen', 'Scott']
folk.splice(2, 1, 'Naomi')

console.log(folk)
// ['Bob', 'Mike', 'Naomi', 'Helen', 'Scott']

The splice started at folk[2] and removed one element (β€˜Sue’) and inserted β€˜Naomi’ at that position in the array.


↑ A to Z of methods

some

The some method returns a boolean based on a given condition. Think back to the every method that returns true if every element matches the condition. Some returns true if some do!

const moreNumbers = [2, 6, 8, 13, 14, 18]
const containsOdd = moreNumbers.some(n => n % 2 != 0)

console.log(containsOdd)
// true

↑ A to Z of methods

sort

The sort method arranges string elements in an array into alpahbetical order.

const people = ['Bob', 'Mike', 'Sue', 'Helen', 'Scott']
people.sort()

console.log(people)
// ['Bob', 'Helen', 'Mike', 'Scott', 'Sue']

If wanting to sort numbers, there be dragons here. Let’s taks a look.

const randomNums = [100, 3, 67, 98, 9, 35]
randomNums.sort()

console.log(randomNums)
// [100, 3, 35, 67, 9, 98]

A really weird result. It has sorted be the first number of the element, not the value. To get around this we need to pass in a function that compares one number with the other, like this:

randomNums.sort((x, y) => x - y);

console.log(randomNums)
// [3, 9, 35, 67, 98, 100]

That fixes the problem. We can even sort them by the highest number first, simply by swapping x and y around.

randomNums.sort((x, y) => y - x);

console.log(randomNums)
// [100, 98, 67, 35, 9, 3]

↑ A to Z of methods

toReversed

The toReversed method is similar to the reverse method but it creates a new array and leaves the orginal alone.

const countUp = [1, 2, 3, 4, 5, 6, 7]
const countDown = countUp.toReversed()

console.log(countUp)
// [1, 2, 3, 4, 5, 6, 7]

console.log(countDown)
// [7, 6, 5, 4, 3, 2, 1]

↑ A to Z of methods

toSorted

The toSorted method is similar to the sort method but it creates a new array and leaves the orginal alone.

const friends = ['Matt', 'Phil', 'Maisey', 'Elsie', 'Bob']
const byAlphabet = friends.toSorted()

console.log(byAlphabet)
// ['Bob', 'Elsie', 'Maisey', 'Matt', 'Phil']

You will remember the numbers sorting kerfuffle above. It has not gone away with toSorted.

const myNums = [100, 3, 67, 98, 9, 35]
const sortedNums = myNums.toSorted((x, y) => x - y);

console.log(sortedNums)
// [3, 9, 35, 67, 98, 100]

↑ A to Z of methods

toSpliced

The toSpliced method is similar to the splice method but it creates a new array and leaves the orginal alone.

const friends = ['Matt', 'Phil', 'Maisey', 'Elsie', 'Bob']

Below we delete the first 2 elements

const lastThreeFriends = friends.toSpliced(0, 2);

console.log(lastThreeFriends)
// ['Maisey', 'Elsie', 'Bob']

Below we add a new friend at position 2

const newFriendArray = friends.toSpliced(2, 0, 'Rhianna');

console.log(newFriendArray)
// ['Matt', 'Phil', 'Rhianna', 'Maisey', 'Elsie', 'Bob']

Below we replace β€˜Bob’ at position 4 with Robert and Sue

console.log(friends.toSpliced(4, 1, 'Robert', 'Sue'))
// ['Matt', 'Phil', 'Maisey', 'Elsie', 'Robert', 'Sue']

↑ A to Z of methods

toString

A string representation of the array elements is created. Nothing more dramatic than that.

console.log(friends.toString())
// Matt,Phil,Maisey,Elsie,Bob

↑ A to Z of methods

unshift

The unshift method is the opposite to shift. It adds an element to the beginning of an array.

const family = ['Jane', 'John']

Jane and John have a baby called Henry

family.unshift('Henry')

console.log(family)
// ['Henry', 'Jane', 'John']

↑ A to Z of methods

values

The values( ) method creates an iterator to loop through an array.

const family = ['Henry', 'Jane', 'John']
const loop = family.values();

for (const person of loop) {
	console.log(person);
}
// Henry
// Jane
// John

↑ A to Z of methods

with

The with method creates a new array with an element that has been modified.

const airlines = ['Air France', 'Al Italia', 'BOAC']

console.log(airlines.with(2, 'British Airways'))
// ['Air France', 'Al Italia', 'British Airways']

And that is it. Array methods allow developers a range of powerful tools to manipulate data for applications. A good example is my Rethinking 2048 blog post on creating the classic 2048 game. In that post you will find examples of the following methods: forEach, push, reverse, and splice. Feel free to come back and use this page as your reference sheet for array methods. Good luck!

Thank you for stumbling across this website and for reading my blog post entitled Array methods in JavaScript