DEV Community

Cover image for Useful array methods with JavaScript
Isabella
Isabella

Posted on

Useful array methods with JavaScript

First, We need to know what's an array and what is used for.

Array is a data structure that consists of a collection of elements (number, boolean, string, object, ...) and we commonly use it to organize and represent a group of elements that are related to each other.

Example: An array of objects that represent users of a system with their year of birth and the role they perform.

const users = [
    { name: "Daniel", birthYear: 1996, role: "Sysadmin" },
    { name: "Sarah", birthYear: 1993, role: "Sysadmin" },
    { name: "Stiven", birthYear: 2000, role: "Tester" },
];
Enter fullscreen mode Exit fullscreen mode

On some occasions we will see it necessary to perform operations with the arrays to filter or obtain information regarding it.

To do this we can use some methods that will allow us to manipulate and extract information regarding the array that we use in a simple way.

Some of these methods are:

 

Filter

Filter helps us to obtain the elements within the array that fulfill a truth condition.

Example: We want to get all the users that their role is "Sysadmin".

truth condition: When users.role is equal to "Sysadmin".

const sysadminUsers = users.filter(user => user.role === "Sysadmin") 
/* returns [{name: "Daniel", birthYear: 1996, role: "Sysadmin"},{name: "Sarah", birthYear: 1993, role: "Sysadmin"}] */
Enter fullscreen mode Exit fullscreen mode

 

Map

Map helps us perform a task on each of the elements of the array.

Example: We want to get the age of each of the users.

const currentYear = new Date().getFullYear();
const AgedUsers = users.map(user => currentYear - user.birthYear);
/* returns [25,28,21] */
Enter fullscreen mode Exit fullscreen mode

 

Some

Some check if one or more elements fulfill a truth condition, if it happens return true else false.

Example: We want to know if exist a user with role "Tester" and "Developer".

 users.some(user => user.role ==="Tester") // returns true
 users.some(user => user.role ==="Developer") // returns false
Enter fullscreen mode Exit fullscreen mode

 

Every

Every check if all elements fulfill a truth condition

const numbers = [1,2,3,4,5,6,7,8,9]
Enter fullscreen mode Exit fullscreen mode

Example: We want to know if all numbers in the above array are greater than 0.

numbers.every(number => number > 0) //returns true
Enter fullscreen mode Exit fullscreen mode

Top comments (0)