Long time, no see. In this article, I'll be explaining and using the top 10 most powerful JS array methods to help boost your JS skills. Whenever I work on my array methods skills, it really boosts my confidence as a developer and helps me work more efficiently on individual and team projects. I can guarantee you'll take on the identity of a way more proficient and confident JS dev after reading this article. Let's get into it!
filter()
filter()
is one of the most commonly used array methods in JavaScript, because of its simple yet powerful functionality. You pass a callback as the function parameter, and any value that returns true for the condition in the callback gets added to a new array.
const arr = [1, 2, 3, 4, 5, 6]
const evenNumbers = arr.filter(i => i % 2 === 0) // [2, 4, 6]
This is the simplest example of filter()
. There are much more advanced cases too, like filtering a dataset from a database.
const arr = [
{name: 'A', posts: 5},
{name: 'B', posts: 8},
{name: 'C', posts: 4},
{name: 'D', posts: 5},
{name: 'E', posts: 7}
]
const users = arr.filter(obj => obj.posts > 5)
/* [ {name: 'B', posts: 8}, {name: 'E', posts: 7} ] */
Hack: You can use the this
keyword inside the callback for additional arguments.
const arr = [
{name: 'A', posts: 5},
{name: 'B', posts: 8},
{name: 'C', posts: 4},
{name: 'D', posts: 5},
{name: 'E', posts: 7}
]
const users = arr.filter(function (obj) {
return obj.posts >= this.min && obj.posts <= this.max
}, { min: 6, max: 8 })
/* [ {name: 'B', posts: 8}, {name: 'E', posts: 7} ] */
I haven't used an arrow function inside the callback because it has different behaviour. this
in an array function refers to the variables in the function's parent scope where it's called.
map()
map()
is an array method that performs a specific function on every value of the array and accordingly creates a new array. This is very powerful in frontend tooling or data modification on a large scale. Just like filter()
, map()
has the this
keyword functionality.
const arr = [
{name: 'A', posts: 5},
{name: 'B', posts: 8},
{name: 'C', posts: 4},
{name: 'D', posts: 5},
{name: 'E', posts: 7}
]
// idx in the callback function specifies the index of the element being processed
const users = arr.map(function (obj, idx) {
obj.followers = this.followers[idx]
return obj
}, { followers: [3, 5, 4, 8, 10] })
// Try it out in your browser console!
reduce()
This array method just reduces our array into an accumulated value. Let me demonstrate with a simple example.
const numbers = [4, 1, 4, 9, 6, 7]
// acc represents accumulator and current represents the current value
const sum = numbers.reduce((acc, current) => acc + current, 0)
// Try it out in your console!
Although the Math
API's min
and max
methods are super easy to use for finding the minimum and maximum values, we can use reduce()
for the same!
const numbers = [4, 3, 6, 8, 1, 5]
const max = numbers.reduce((max, num) => num > max ? num : max, -Infinity)
const min = numbers.reduce((min, num) => num < min ? num : min, Infinity)
// Try it out in your console!
sort()
As the name implies, sorting. The algorithm that runs under the hood to sort your array is called bubble sort. If you'd like to learn more about it, I've written an entire blog post just for you. The return value of the callback function in sort()
has to be either an integer more than 1, zero or less than 1. If it's more than 1, then the first element will appear after the second element, and vice-versa. If it's zero, the original order will be retained. Here's how you sort an array of numbers in increasing and decreasing order. Also, note that sort()
mutates the array. To create a copy of the sorted array, I'm using toSorted()
in this case.
const numbers = [4, 3, 6, 8, 1, 5]
const increasingOrder = numbers.toSorted((a, b) => a - b)
const decreasingOrder = numbers.toSorted((a, b) => b - a)
So simple! To learn more about sort()
, I highly recommend reading this informative article I found on Hashnode: 5 useful tips about the JavaScript array sort method
some()
This array method does not modify the original array or return a new array. It simply returns a boolean value indicating whether or not any element in the array satisfies the condition in the callback.
const marksOfStudents = [88, 74, 34, 60, 72, 99]
// Checks whether any student at all has scored above 70
console.log(marksOfStudents.some(marks => marks > 70))
every()
Absolutely similar to some()
, just for all the elements in the array.
const marksOfStudents = [88, 74, 64, 60, 72, 99]
// Checks whether all the students have scored less than or equal to 60
console.log(marksOfStudents.every(marks => marks <= 60))
Also, some()
and every()
do not run on empty slots in an array.
console.log([3, , 3].every(x => x == 3)) // true
find()
Probably the simplest array method. Period.
const numbers = [8, 45, 32, 6, 29]
console.log(numbers.find(num => num > 40))
// 45
// The first element that satisfies the condition is returned
findIndex()
Just like find()
, except it returns the index of the first element in the array satisfying the condition in the callback.
const numbers = [8, 45, 32, 6, 29]
console.log(numbers.findIndex(num => num > 40))
slice()
This array method takes two arguments, a start index and an end index. It returns a portion of the array starting from the start index and the element before the end index. It doesn't modify the original array. You'll best understand this by seeing the following examples.
const numbers = [8, 45, 32, 6, 29]
console.log(numbers.slice(2)) // [32, 6, 29]
console.log(numbers.slice(2, 4)) // [32, 6]
console.log(numbers.slice(-2)) // Last two elements of the array, [6, 29]
console.log(numbers.slice(-2, -1)) // [6]
splice()
This method is almost the same as slice()
, except it takes in another optional argument and also modifies the original array. To not modify the original array in my example, I'll use toSpliced()
.
splice()
takes three arguments: a starting point, the number of elements to remove (optional), and the elements to add (optional).
const numbers = [8, 45, 32, 6, 29]
console.log(numbers.toSpliced(numbers.length, 0, ...[88, 77])) // Adds 88 and 77 to the array
console.log(numbers.toSpliced(numbers.length, 0, 88, 77) // Same result as above
console.log(numbers.toSpliced(1, 3)) // [8, 29]
Thanks for reading this article! If you found it helpful, please click the favourite button and write a helpful comment. I'd love some feedback, and the comments section is the best place for you to give some. If you're more interested in JavaScript and Web Dev articles, check out my blog to learn more, thrice a week!