Having useful array methods at the top of your head will improve your problem solving ability.
So I decided to make a JavaScript array methods cheat sheet so I can quickly revise array methods and always keep them fresh in my mind.
This cheat sheet includes 17 commonly used array methods:
**- toString()
- join()
- concat()
- splice()
- slice()
- indexOf()
- lastIndexOf()
- forEach()
- map()
- filter()
- reduce() **
# Array methods in JavaScript 1.### toString
Converts an array into a string of comma-separated array values:
let names = ["Zoe", "Adam", "Dan"]
let strNames = names.toString() // Zoe,Adam,Dan
join
Similar to toString, but you can specify the separator:
let names = ["Zoe", "Adam", "Dan"]
let strNames = names.join(" and ") // Zoe and Adam and Dan
concat
Create a new array by concatenating existing arrays:
let nums = [1, 2, 3]
let nums2 = [4, 5, 6]
let nums3 = [7, 8, 9]
let concatArr = nums.concat(nums2, nums3)
// [1, 2, 3, 4, 5, 6, 7, 8, 9]
splice
The splice() method can be used to add new items to an array:
let arr = ["Danny", "Joe"]
arr.splice(1, 0, "Alice", "Amy")
console.log(arr) // ['Danny', 'Alice', 'Amy', 'Joe']
The first parameter (1) defines the index from where the new elements should be added (spliced in).
The second parameter (0) defines how many elements should be removed.
The rest of the parameters ('Alice', 'Amy') define the new elements to be added.
splice() returns an array with the deleted items:
let arr = ["Danny", "Joe"]
let spliced = arr.splice(1, 1, "Alice", "Amy") // ['Joe']
console.log(arr) // ['Danny', 'Alice', 'Amy']
We can also delete items without adding any new ones:
let arr = ["Danny", "Joe", "Amy"]
let spliced = arr.splice(1, 1) // ['Joe']
console.log(arr) // ['Danny', 'Amy']
Since splice() mutates the original array, it is often best to make a copy of it before splicing.
slice
slice() slices out a piece of an array, and returns it in a new array:
let arr = ["Danny", "Joe", "Amy"]
let slice = arr.slice(1) // ['Joe', 'Amy']
Above, we are slicing from the element at index 1. slice() does not mutate the original array.
We can provide a start and end index to splice from (up to but not including end index):
let arr = ["Danny", "Joe", "Amy"]
let slice = arr.slice(0, 2) // ['Danny', 'Joe']
indexOf
Find the first index that contains a certain value (searches from left to right):
let arr = ["Danny", "Joe", "Amy", "Joe"]
let index = arr.indexOf("Joe") // 1
lastIndexOf
Find the last index that contains a certain value (searches from right to left):
let arr = ["Danny", "Joe", "Amy", "Joe"]
let index = arr.lastIndexOf("Joe") // 3
forEach
The forEach method is basically just a shorter way of writing for(let i = 0; i < arr.length; i++) {...}.
It loops through the given array, and calls the given call-back function for each of the elements in the array.
The call-back passed to the forEach() function can accept any of the three arguments:
**- the item value
- the item index
- the array itself**
Example:
let numbers = [1, 2, 3, 4]
numbers.forEach(n => console.log(n))
// 1
// 2
// 3
// 4
map
The map function takes in a call-back function as argument, and executes that function on each element of the array it is working on. It maps each of the return values of the call-back into a new array. It does not mutate the original array.
The call-back passed to the map() function can accept any of the three arguments:
- **the item value
- the item index
- the array itself**
Examples:
let numbers = [1, 2, 3, 4]
// Double all numbers
let doubledNumbers = numbers.map(n => n * 2) // [2, 4, 6, 8]
// Only double numbers at odd indexes
let doubledOddIndexNumbers = numbers.map((n, i) => {
if (i % 2 === 1) return n * 2
else return n
}) // [1, 4, 3, 8]
filter
The filter method is used to filter out array elements that fail a boolean test. Only elements that pass the test are allowed through into the new return array.
The call-back passed to the filter() function can accept any of the three arguments:
- **the item value
- the item index
- the array itself** A good use case for filter is a search bar:
let articles = [
{ title: "PHP classes", author: "Danny Adams" },
{ title: "Python arrays", author: "Amy Sanders" },
{ title: "Arrays in PHP", author: "Danny Adams" },
]
// Lets say the user searches for all articles with PHP in the title
let PHPArticles = articles.filter(a => a.title.includes("PHP"))
// [
// { title: 'PHP classes', author: 'Danny Adams' },
// { title: 'Arrays in PHP', author: 'Danny Adams' },
// ];
reduce
The reduce method runs the call-back function on each array element, and reduces the array down into a single value.
The reduce function itself takes two arguments:
- **A call-back function
- An initial value** reduce(callback, initialVal)
The call-back function passed into reduce can take up to four arguments:
- **total or "accumulator"
- current item value
- current item index
- the array itself** Example:
let numbers = [1, 2, 3, 4]
let total = numbers.reduce((total, currentNum) => total + currentNum) // 10
In the above example, total is initially the first value in the array (1), and currentNum is the second (2).
If we wanted to start from a different value, we can pass in a second initialVal argument to reduce. Let's say we wanted to find the total, starting from 5:
let numbers = [1, 2, 3, 4]
let total = numbers.reduce((total, currentNum) => total + currentNum, 5) // 15
Above, total will now start out as 5, and currentNum will be the first element in the array (1).
Another good use case of reduce is to find the max or min value in an array:
let arr = [1, 2, 3]
let max = arr.reduce((a, b) => {
return Math.max(a, b)
}, -Infinity)
// 3