Here is a rundown of some useful array methods in JavaScript. Each method listed below will include the following:
- A description of what it does
- Brief explanation of how it works
- Time complexity (if appropriate)
- three code examples
Here is a list of all the methods I will cover, in case you want to jump to a particular section!
Map
Reduce
Filter
ForEach
Sort
Slice
Pop
Shift
Unshift
Push
Includes
IndexOf
Every
Array.prototype.map() returns a new array, with each element of that array modified based on a function that you pass into it.
Map is not destructive to the original array.
Parameters accepted:
A callback function which can accept the following as parameters:
- the current element of the array (required)
- the index of the current element
- the array that map was called on
In addition to the callback function, it can also take in a value to use as this
when calling the callback function
Basic usage:
someArray.map(el => //return statement)
Some examples:
const arr = ['Apple', 'Peach', 'Orange'] arr.map(el => el + '!')
// returns [ "Apple!", "Peach!", "Orange!" ]
const arr = ['Apple', 'Peach', 'Orange']
arr.map((el, i) => i)
// returns [ 0, 1, 2 ]
const arr = ['Apple', 'Peach', 'Orange']
arr.map((el, i) => {
return (i % 2 === 0) ? el.toUpperCase() : el
})
// returns [ "APPLE", "Peach", "ORANGE" ]
Array.prototype.reduce() uses something called a reducer function, which is called on the array that reduce is called on. What happens is the array is eventually reduced to one value, which becomes the return value of .reduce()!
Reduce is unique in that it also takes in a special (optional) initial value to kick off the .reduce() function.
Reduce will not affect the original array.
Parameters accepted:
The reducer function is passed to reduce, and can take four arguments:
- the accumulator (required)
- the current value (required)
- the current index
- the array that .reduce() was called on
Don’t forget - .reduce() can also take an optional initial value.
Basic usage:
someArray.reduce(reducerFunction, initialValue)
or
someArray.reduce((acc, curr) => acc + curr, 0)
Some examples:
const arr = [1,2,3,4,5] arr.reduce((a, b) => a + b)
// returns 15
const arr = ['1','2','3','4','5'] arr.reduce((a, b) => a + b)
// returns "12345"
const arr = ['1','2','3','4','5'] arr.reduce((a, b) => a - b, 15)
// returns 0
Array.prototype.filter() will ‘filter’ an array based on a function that is passed into it. The function checks each element of the array, and the elements that pass the test will be returned in a new array!
Filter is not destructive to the original array.
Parameters accepted:
.filter() takes in a function which itself can take up to three parameters:
- the current element (required)
- index of the current element
- the array that .fliter() was called on
In addition to the callback function, it can also take in a value to use as this
when the function is called
Basic usage:
someArray.filter(el => callbackFunction)
Some examples:
const arr = [1,2,3,4,5,6,7,8] arr.filter(el => el % 2 === 0)
//returns [ 2, 4, 6, 8 ]
const arr = ['short', 'sesquipedalian', 'words', 'obsequious', 'only']
arr.filter(el => el.length < 6) //returns [ 2, 4, 6, 8 ]
//returns [ "short", "words", "only" ]
const arr = ['foo', 'bar', 'buzz', 'bat', 'hello']
arr.filter((el, i) => i % 2 === 0)
// returns even index items only: [ "foo", "buzz", "hello" ]
Array.protoype.forEach() executes a function for each element in an array. It’s very much like a for
loop. It does not affect the original array, and it returns undefined
!
Parameters accepted:
.forEach() takes a callback function much like the other Array methods we’ve studied so far. That function can take up to three parameters:
- the current element (required)
- the index of that element
- the array that .forEach() is being called on
In addition to the callback function, it can also take in a value to use as this
when the function is called
Basic usage:
someArray.forEach(el => callbackFunction)
Some examples:
const arr = ['Alan', 'Al', 'Alan', 'Allen', 'Alan'] const newArr = arr.forEach(el => console.log(el.concat('!')))
//will print the following to the console: Alan! Al! Alan! Allen! Alan!
const arr = ["chocolate chip cookie", "dried fruit", "candy", "sugar cookie", "bagel", "peanut butter cookie", "peanuts"] const cookies = [] const otherSnacks = [] arr.forEach(el => (el.includes('cookie')) ? cookies.push(el) : otherSnacks.push(el)) console.log(cookies, otherSnacks)
// prints cookies array and otherSnacks array:
[ "chocolate chip cookie", "sugar cookie", "peanut butter cookie" ]
[ "dried fruit", "candy", "bagel", "peanuts" ]
const arr = [12, 13, 15, 62, 67, 48] arr.forEach(el => { console.log(`${el} is${(el % 4 === 0) ? "" : " not"} a multiple of 4.`) })
// prints the following:
12 is a multiple of 4.
13 is not a multiple of 4.
15 is not a multiple of 4.
62 is not a multiple of 4.
67 is not a multiple of 4.
48 is a multiple of 4.
Array.prototype.sort() sorts an array as strings by default, with smaller values first. It determines which one is smaller by checking the Unicode code point values.
.sort() sorts items “in place”, which means that the original array is changed.
Time complexity: O(n∗logn)O(n *\log{}n)O(n∗logn)
This can vary depending on what JS engine (or browser) is being used, and how many elements are in the array.
Parameters accepted:
The way sort works is it compares as strings by default, but you can pass a compare function to it. If a compare function is used, the items will be sorted by the return value of the compare function.
The compare function can take in two values:
- the first element
- the next element
Basic usage:
someArray.sort((a, b) => compareFunc}
compareFunc(a, b){ if (a < b) return -1 if (a > b) return 1 return 0 }
or
someArray.sort((a, b) => a - b)
Some examples:
const names = ['Isabelle', 'Chevre', 'Aurora', 'Tom', 'Blathers', 'Brewster'] names.sort()
//returns: [ "Aurora", "Blathers", "Brewster", "Chevre", "Isabelle", "Tom" ]
const nums = [17,38,3,14,5,21,22,4]
console.log(nums.sort())
//prints:
[ 14, 17, 21, 22, 3, 38, 4, 5 ]
console.log(nums.sort((a,b) => a - b))
//prints:
[ 3, 4, 5, 14, 17, 21, 22, 38 ]
const nums = [32,56,43,57,12,34]
nums.sort((a,b) => b - a)
//returns:
[ 57, 56, 43, 34, 32, 12 ]
Array.prototype.slice() extracts part of an array and then returns it.
It’s kind of like a slice of an array!
It does not affect the original array… however, if the the items in the arrays are objects, the new array will reference those objects. This means that if you try to alter an object in the new array, the original objects will be affected as well.
Parameters accepted:
.slice() can take two parameters:
- start
- end
start
indicates at which index the slice will begin, and end
indicates the index where the slice ends. start
will be included in the returned array, and the value at end
will not.
You can use a negative number for start
, which will cause .slice() to count from the end of the array.
If start
is too large for the array, and empty array will be what comes back.
The value passed in as end
works much like start
, except that if it’s too large for the array, it will just count through the end of the array
Basic usage:
someArray.slice(start, end)
Some examples:
const arr = [ 1, 2, 3, 4, 5, 6, 9] arr.slice()
//returns [ 1, 2, 3, 4, 5, 6, 9 ]
const arr = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
arr.slice(-3)
//returns: [ "e", "f", "g" ]
const arr = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
arr.slice(2, 100)
//returns: [ "c", "d", "e", "f", "g" ]
const arr = [{name: "bob", rank: 10},{name: "helen", rank: 11},{name: "ariel", rank: 9}]
const slicedArr = arr.slice(0, 2)
slicedArr[0].rank = 22
console.log(arr[0], slicedArr[0])
//prints:
{ name: "bob", rank: 22 }
{ name: "bob", rank: 22 }
Array.prototype.pop() “pops” an element off of the end of an array, and returns it. It returns undefined
if it’s called on an empty array.
It affects the original array!
You can use .pop() on array-like objects by using .call(arrayLikeObj).
See the last example.
Parameters accepted:
none!
Basic usage:
someArray.pop()
Some examples:
const trees = ["oak", "spruce", "birch", "cedar"]
trees.pop()
//returns: "cedar"
console.log(trees)
//prints: [ "oak", "spruce", "birch" ]
const fruits = ["kiwi", "orange", "banana"] //using slice to copy the fruits array, so we don't affect it! const lastFruit = fruits.slice().pop() console.log(fruits, fruitsCopy)
//prints: [ "kiwi", "orange", "banana" ] banana
const things = { 0:'thing1', 1:'thing2', 2:'thing3', length: 3} //needs the length propoerty
const poppedThing = Array.prototype.pop.call(things)
console.log(things, poppedThing)
//prints:
{ 0: "thing1", 1: "thing2", length: 2 }
thing3
`
Here’s something really cool you can do with this method. You can use it in a loop like this:
const arr = [1,2,3,4,5] while (typeof (i = arr.pop()) !== 'undefined') { console.log(i) }
//prints: 5 4 3 2 1
Array.prototype.shift() behaves just like .pop(), except it works on the beginning, or front of the array.
It affects the original array.
Parameters accepted:
none!
Basic usage:
someArray.shift()
Some examples:
const arr = ['pink', 'purple', 'blue', 'grey'] arr.shift()
//returns: "pink"
console.log(arr)
//prints: [ "purple", "blue", "grey" ]
const arr = ['bread', 'nacho cheese', 'lettuce', 'macaroni'] while ((i = arr.shift()) !== undefined) { console.log(i) }
//prints: bread nacho cheese lettuce macaroni
Array.prototype.unshift() is kind of like the opposite of .shift() - instead of removing an item from the beginning, or the front of an array, it adds an item (or more).
It modifies the original array, and its return value is the new length of the array.
Parameters accepted:
- the element to add to the array
Basic usage:
someArray.unshift(newElement)
Some examples:
const dinosaurs = ['stegosaurus', 'triceratops', 'diplodocus'] dinosaurs.unshift('ankylosaurus') // returns: 4
console.log(dinosaurs) //prints: [ "ankylosaurus", "stegosaurus", "triceratops", "diplodocus" ]
const weekdays = ['thu', 'fri', 'sat']
weekdays.unshift('mon', 'tue', 'wed')
//returns: 6
console.log(weekdays)
//prints: [ "mon", "tue", "wed", "thu", "fri", "sat" ]
const outOfOrder = ['thu', 'fri', 'sat']
outOfOrder.unshift('mon') //returns 4
outOfOrder.unshift('tue') //returns 5
outOfOrder.unshift('wed') //returns 6
console.log(outOfOrder)
//prints: [ "wed", "tue", "mon", "thu", "fri", "sat" ]
Array.prototype.push() is similar to .shift(), except it adds one or more items to the end of an array.
It changes the original array, and the return value is the new length of the array.
Parameters accepted:
- the element to add to the array
Basic usage:
someArray.push(newElement)
Some examples:
const names = ['aria', 'pokey', 'mitsy'] names.push('oreo') //returns: 4
console.log(names) prints: [ "aria", "pokey", "mitsy", "oreo" ]
const fish = ['bass', 'char', 'salmon']
fish.push('angelfish', 'parrotfish', 'sturgeon')
//returns: 6
console.log(fish)
//prints: [ "bass", "char", "salmon", "angelfish", "parrotfish", "sturgeon" ]
const inventory = [{0: 'chamomile', qty: 6}, {1: 'hibiscus', qty: 2}, {2: 'peppermint', qty: 10}]
inventory.push({3: 'rooibos', qty: 10}, {4: 'linden', qty: 10})
//returns: 5
console.log(inventory)
//prints the following:
// an Array, [ {…}, {…}, {…}, {…}, {…} ] containing...
0: Object { 0: "chamomile", qty: 6 }
1: Object { 1: "hibiscus", qty: 2 }
2: Object { 2: "peppermint", qty: 10 }
3: Object { 3: "rooibos", qty: 10 }
4: Object { 4: "linden", qty: 10 }
length: 5
Array.prototype.includes() checks to see if a value passed into it exists in an array.
It returns true
if it is found, and false
if not.
Parameters accepted:
- element to search for (required)
- index to start the search from
Basic usage:
someArray.Method(el, index)
Some examples:
const arr = [1, 2, 3, 4, 5]
console.log(arr.includes(2)) //true
console.log(arr.includes(0)) //false
const words = ['well', 'hello', 'there']
console.log(words.includes('hello')) //true
console.log(words.includes('the')) //false
const arr = ['a', 'b', 'c', 'd', 'e']
arr.includes('b', 0) //true
arr.includes('b', 2) //false
arr.includes('b', -3) //false
arr.includes('b', -4) //true - starts search at 4 from end
Array.prototype.indexOf() searches an Array for an element, and returns the index number of where that item is located.
If it’s not found, -1 will be returned.
The element that is being searched for has to match in both value and type for a match to happen. (i.e., ‘3’ and 3 will not match.)
Parameters accepted:
- the element to find in the array (required)
- index where the search will start
Basic usage:
someArray.indexOf(el, index)
Some examples:
const animals = ['zebra', 'buffalo', 'nuthatch', 'puma']
animals.indexOf() // -1
animals.indexOf('nuthatch') // 2
animals.indexOf('Puma') // -1
const nums = [1, 2, 3, 4, 6]
const n = await nums.indexOf(5)
if (n === -1) {
return 'not found'
} else {
return `found at index: ${n}`
}
// returns: "not found"
const nums = [1, 2, 3, 4, 6]
function addNum(n, arr){ arr.push(n) arr.sort() }
function isInArray(n, arr){ if (arr.indexOf(n) == -1) { console.log(n + " is not in the array") addNum(n, arr) } else { console.log(n + " is already in the array") } }
isInArray(5, nums) //prints: "5 is not in the array" console.log(nums) //prints: [ 1, 2, 3, 4, 5, 6 ]
Array.prototype.every() checks to see if every item passes a test that is given by a function.
If every element in the array has a ‘truthy’ value, .every() will return true
. Otherwise it’ll return false
.
Parameters accepted:
.every() takes in a callback function, which itself can take three arguments:
- the current element (required)
- the index of the current element
- the original array that .every() was called on
In addition to the callback function, it can also take in a value to use as this
when the function is called.
Basic usage:
someArray.every((el, index) => callbackFunc)
Some examples:
const arr = [5, 4, 7, 29, 90]
arr.every(el => el > 0) //returns: true
arr.every(el => el > 5) //returns: false
const duckDuckGoose = ['duck', 'duck', 'goose'] const duckDuckDuck = ['duck', 'duck', 'duck']
function isDuck(str){ return str === 'duck' }
console.log(duckDuckGoose.every(isDuck)) //prints: false console.log(duckDuckDuck.every(isDuck)) //prints: true
const nums = [[1, 2, 16], [0, 101, 2], [99, 78, 34]]
nums.forEach(arr => {
console.log(`${JSON.stringify(arr)}... are all nums less than 100? `+ arr.every(el => el < 100))
})
//prints:
[1,2,16]... are all nums less than 100? true
[0,101,2]... are all nums less than 100? false
[99,78,34]... are all nums less than 100? true
That’s it!
Thanks for taking the time to check out my little reference manual on Array Methods.
Go forth and use the aforementioned methods to your heart’s content ✨
The ultimate reference for JavaScript features can be found at the MDN WebDocs