DEV Community

Cover image for JavaScript Array Methods: A Comprehensive Guide
Luca Spezzano
Luca Spezzano

Posted on • Originally published at Medium

JavaScript Array Methods: A Comprehensive Guide

Top JavaScript Array Methods with Real-World Examples

JavaScript arrays methods are a very powerful for organizing and manipulating data natively.

While there are many articles and examples available online for working with arrays in JavaScript, these examples often only cover arrays of strings or numbers. In reality, a more common scenario is working with arrays of objects, especially when making API calls.
Therefore, it can be useful to have a list of the most useful array methods and examples specifically for working with arrays of objects.

Today, I would like to share some of the most useful array methods that I have found helpful when working with arrays of objects.

Get an array of objects with a key “status” equal to “active” from an array of objects in JavaScript


let listUser = [
  { id: 1, name: 'Alice', status: 'active' },
  { id: 2, name: 'Bob', status: 'inactive' },
  { id: 3, name: 'Charlie', status: 'active' },
  { id: 4, name: 'Dave', status: 'active' }
];

let activeUsers = listUser.filter(object => object.status === 'active');

console.log(activeUsers); 

// [{ id: 1, name: 'Alice', status: 'active' }, { id: 3, name: 'Charlie', status: 'active' }, { id: 4, name: 'Dave', status: 'active' }]

Enter fullscreen mode Exit fullscreen mode

The filter() method creates a new array with all elements that pass the test function provided. In this case, the test function checks if the status property of the object is equal to 'active'. If it is, the object is included in the new array. If it is not, it is not included.

Find an object with a specific ‘id’ in an array using JavaScript

let listUser = [
  { id: 1, name: 'Alice' },
  { id: 2, name: 'Bob' },
  { id: 3, name: 'Charlie' },
  { id: 4, name: 'Dave' }
];

let result = listUser.find(object => object.id === 3);

console.log(result); 
// { id: 3, name: 'Charlie' }
Enter fullscreen mode Exit fullscreen mode

The find() method returns the value of the first element in the array that satisfies the provided testing function. In this case, the testing function checks if the id property of the object is equal to 3. If it is, the object is returned. If it is not, undefined is returned.

If you like, you can check out the full article with more examples on Medium 👇

If you are not able to read the article, in the comments is present the friend link ;)

Top comments (1)

Collapse
 
93lucasp profile image
Luca Spezzano