In this article, we'll learn about the array methods in JavaScript with some examples. Before we start, let's look at some methods of the Array
class.
Array()
Accepts 1 integer argument and returns an array with those elements.
Array(10) // Array(10) [ <10 empty slots> ]
Array() // Array []
.from()
We use this method to create an array. It accepts two arguments, the first one accepts an array or some iterable object.
Array.from("never") // Array(5) [ "n", "e", "v", "e", "r" ]
The second argument is for the mapping function (scroll below to learn more about map), it is optional.
Array.from("never", (el, i) => el + i)
// Array(5) [ "n0", "e1", "v2", "e3", "r4" ]
.isArray()
This method accepts 1 argument and returns if it's an array.
Array.isArray("") // false
Array.isArray() // false
Array.isArray(42) // false
Array.isArray([]) // true
Now, we'll go to the main part of this article.
.at()
Returns the element of the array of the given position. You can use negative numbers instead of doing array[array.length-1]
.
["a","b","c","d","e"].at(0) // a
["a","b","c","d","e"].at(-1) // e
["a","b","c","d","e"].at(42) // undefined
.concat()
Merges all the arguments to one array.
["hello"].concat("world", "bye", "world", [5])
// Array(5) [ "hello", "world", "bye", "world", 5 ]
.copyWithin()
Copies the array within a range. Accepts 3 arguments.
["1","2","3","4","5","6"].copyWithin(0)
// Array(6) [ "1", "2", "3", "4", "5", "6" ]
["1","2","3","4","5","6"].copyWithin(3, 0)
// Array(6) [ "1", "2", "3", "1", "2", "3" ]
["1","2","3","4","5","6"].copyWithin(3, 0, 4)
// Array(6) [ "1", "2", "3", "1", "2", "3" ]
.every()
Accepts a test function and returns a boolean if all the elements of the array pass the test.
["gonna", "give", "you"].every((element) => element.startsWith("g")) // false
["apple", "android", "aluminium"].every((element) => element.startsWith("a")) // true
.fill()
Fills the array with a given value. Accepts 3 arguments. 1st argument is the value we need to fill. The 2nd argument is the starting index. The last argument is the ending index. The last two parameters are optional.
Array(10).fill(1) // Array(10) [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
Array(10).fill(1, 5)
// Array(10) [ <5 empty slots>, 1, 1, 1, 1, 1 ]
Array(10).fill(1, 2, 4)
// Array(10) [ <2 empty slots>, 1, 1, <6 empty slots> ]
.filter()
Accepts a test function to loop each array element and remove that element if failed the test.
["eating", "sleeping", "coding", "playing"].filter(element => element != "sleeping")
// Array(3) [ "eating", "coding", "playing" ]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10].filter(element => element % 2)
// Array(5) [ 1, 3, 5, 7, 9 ]
.find()
Again, this accepts a test function and returns the element that the test function passed.
const people = ["John", "Anna", "Peter", "Rick", "Elon"]
const search = name => people.find(element => element.startsWith(name))
search("Jo") // "John"
search("Rick") // "Rick"
search("Ben") // undefined
.findIndex()
Does the same thing as .find()
. Instead of returning the value, returns the position of the element in the array.
const people = ["John", "Anna", "Peter", "Rick", "Elon"]
const search = name => people.findIndex(element => element.startsWith(name))
search("Jo") // 0
search("Rick") // 3
search("Ben") // -1
.flat()
Flats the array to a given depth. The depth will be 1 if no value.
[1, [2, [3, [4]]], 5].flat() // Array(4) [ 1, 2, (2) [β¦], 5 ]
[1, [2, [3, [4]]], 5].flat(2) // Array(5) [ 1, 2, 3, (1) [β¦], 5 ]
[1, [2, [3, [4]]], 5].flat(3) // Array(5) [ 1, 2, 3, 4, 5 ]
.forEach()
Accepts an argument that will call for each element of the array
["one","two","three","four"].forEach(alert) // Alerts 4 times
.includes()
Returns if the array contain the given value. Also, this is case-sensitive.
["ant","bat","cat","rat","man"].includes("man") // true
["ant","bat","cat","rat","man"].includes("Man") // false
["ant","bat","cat","rat","man"].includes("dog") // false
.indexOf()
Returns the least index of an element of the array (if found) after searching the value. Returns -1 if not found. The 2nd argument specifies the position to start the search.
["ant","bat","cat","rat","man"].indexOf("man") // 4
["ant","bat","cat","rat","man"].includes("Man") // -1
["ant", "bat", "cat", "rat", "man"].includes("ant", 2) // -1
.join()
Joins all the array elements into a string with a separator (if given).
["up", "never", "gonna", "let", "you", "down"].join` `
.lastIndexOf()
Does the same thing as .indexOf
. Instead of giving the least index, this gives you the largest index.
["a", "aaa", "aaa", "aa", "a", "aaa"].lastIndexOf("aaa") // 5
["a", "aaa", "aaa", "aa", "a", "aaa"].lastIndexOf("b") // -1
.map()
Loops for each element of the array and executes the given function and change the value to the output of the function.
["a","b","c","d","e","f","g"].map(e=>e.toUpperCase())
// Array(7) [ "A", "B", "C", "D", "E", "F", "G" ]
.pop()
Removes the last element of the array and returns it. (You may know stack operations)
let arr = ["a","b","c","d","e","f","g"]
console.log(arr.pop()) // g
console.log(arr) // ["a","b","c","d","e","f"]
.shift()
Removes the first element and return that element.
let arr = ["a","b","c","d","e","f","g"]
console.log(arr.shift()) // a
console.log(arr) // ["b","c","d","e","f","g"]
.push()
Push the given value to the array. Then, return the new length of the array.
let h = ["hello"]
console.log(h.push("world")) // 2
console.log(h) // Array [ "hello", "world" ]
.unshift()
Does the same as .push
but adds the elements to the first.
let h = ["hello"]
console.log(h.unshift("world")) // 2
console.log(h) // Array [ "world", "hello"]
.reduce()
Accepts a reducer function as the first argument and executes it. If you can't understand that, see below. The second arguments show the initial value, and it's optional.
To calculate the sum of an array, we can do this.
let tot = 0
const array = [1, 2, 3, 4, 5]
array.forEach(e => (tot += e))
console.log(tot) // 15
There is no problem of doing that, but we can use .reduce() to that.
const tot = [1, 2, 3, 4, 5].reduce((previous, current) => previous + current, 0)
console.log(tot) // 15
.reduceRight()
Same as .reduce()
but executes from the last to start of the array. If we do a quick test, we can see this.
[1, 2, 3, 4, 5].reduceRight((previous, current) => {
console.log("current: ", current)
return previous + current
})
Outputs
.reverse()
Reverse the array!
[1, 2, 3, 4, 5].reverse() // Array(5) [ 5, 4, 3, 2, 1 ]
.slice()
Imagine cutting an array like cutting a vegetable. This method does the same. It accepts 2 arguments. The start index and the end.
["head","neck","body","feet"].slice() // (same array)
// WARNING : weird creatures ahead
["head","neck","body","feet"].slice(1)
// Array(3) [ "neck", "body", "feet" ]
["head", "neck", "body", "feet"].slice(1, 3)
// Array [ "neck", "body" ]
.some()
Accepts a function that tests and returns if one or more elements of the array passes that.
const ages = [42, 69, 1, 25, 34, 14]
ages.some(age => age > 60) // true
.sort()
Sorts an array and returns the sorted array. You can also use your own sorting function.
[1, 2, 4, 8, 4, 2, 1, 6, 8, 4, 2, 7, 56, 2, 9, 5, 52, 1].sort()
// Array(18) [ 1, 1, 1, 2, 2, 2, 2, 4, 4, 4, β¦ ]
Using your own sorting function
let people = [{
name: "Andrew",
age: 19
}, {
name: "Posandu",
age: 14
}, {
name: "Luke",
age: 17
},
{
name: "Ben",
age: 23
}
]
console.log(people.sort((a, b) => a.age > b.age))
/*
0: Object { name: "Posandu", age: 14 }
1: Object { name: "Luke", age: 17 }
2: Object { name: "Andrew", age: 19 }
3: Object { name: "Ben", age: 23 }
*/
And that's all you need to learn about the array methods in JavaScript! I publish more like this on my blog https://www.tronic247.com/
Top comments (2)
Looking through this list reminds me why as developers we sometimes need to refer to the documentation there is so much to remember π Great guide by the way.
thanks!