DEV Community

Cole Walker
Cole Walker

Posted on

4 Awesome Array Methods in JavaScript

Arrays are one of the most commonly used data structures in JavaScript, and they have a lot of awesome methods that make development a bit easier for us. Here are a few of my favorite array methods.

Set

While not technically an array method, I often use this data structure to filter out duplicates from arrays storing primitive types. A Set is a data structure which stores unique values, making it a simple way of eliminating duplicates in arrays.

const arr = [1,2,2,3,3,3]
const filteredArr = [...new Set(arr)]   // [1,2,3]

Filter

When you have more complex data structures stored in your arrays, and need to remove duplicates or only some of the items, filter is the way to go. Filter allows you to return a new array containing any elements which pass a test of your choice.

const arr = [1,2,2,3,3,3]
const filteredArr = arr.filter((value, index, self) => {
    return self.indexOf(value)===index)
} 

The above snippet passes each item of the array into the filter function, which will check to see if it is the first occurrence of its value. If it isn't, then that means it's a duplicate, and it will be removed.

Some

Array.some is a neat method which returns true if any element of an array matches a condition. I often use this method in conjunction with filter to filter my arrays with more complex logic.

/* I use the arrow function implicit return syntax here 
to make the code easier to read. 
If you aren't familiar with the syntax, 
the arrow function returns the value of the statement 
following it.
*/
const arr = [1,2,3,4,5]
const contains1 = arr.some((value) => value===1) // true
const contains6 = arr.some((value) => value===6) // false

All

Array.all is exactly what you think it is. It returns true only if every element in an array matches a condition. While I don't use this function as frequently as the others on this list, it is great to have in my back pocket.

const all1 = [1,1,1]
const arr = [1,1,2]
const all1Only1 = all1.all((value) => value===1) //true
const arrOnly1 = arr.all((value) => value===1) //false

Top comments (0)