This site uses tracking technologies. You may opt in or opt out of the use of these technologies.

Back to Javascript

Javascript working with arrays of objects

Working with arrays of objects in JavaScript is common when managing lists of data, like users, products, or any structured information.

1. Filtering - filter()

Use filter() to create a new array with objects that meet a specific condition.

1const users = [
2 { name: "Alice", age: 25 },
3 { name: "Bob", age: 30 },
4 { name: "Charlie", age: 25 },
5];
6
7// Filter users by age
8const age25Users = users.filter(user => user.age === 25);
9console.log(age25Users); // [{ name: "Alice", age: 25 }, { name: "Charlie", age: 25 }]
10

2. Finding - find()

The find() method returns the first object that matches a condition.

1const user = users.find(user => user.name === "Bob");
2console.log(user); // { name: "Bob", age: 30 }
3

3. Mapping - map()

Use map() to create a new array by transforming each object.

1const names = users.map(user => user.name);
2console.log(names); // ["Alice", "Bob", "Charlie"]
3

4. Sorting - sort()

The sort() method allows sorting the array based on object properties.

1const sortedByAge = [...users].sort((a, b) => a.age - b.age);
2console.log(sortedByAge);
3

5. Reducing - reduce()

The reduce() method accumulates values in the array, useful for summing or aggregating data.

1const totalAge = users.reduce((acc, user) => acc + user.age, 0);
2console.log(totalAge); // 80
3

6. Checking Conditions - some() and every()

  • some() checks if at least one element matches a condition.

  • every() checks if all elements match a condition.

1const hasYoungUser = users.some(user => user.age < 30);
2console.log(hasYoungUser); // true
3
4const allUsersAreAdults = users.every(user => user.age >= 18);
5console.log(allUsersAreAdults); // true
6

7. Grouping by Property

Grouping can be done using reduce() for complex structures.

1const groupedByAge = users.reduce((group, user) => {
2 const age = user.age;
3 if (!group[age]) group[age] = [];
4 group[age].push(user);
5 return group;
6}, {});
7
8console.log(groupedByAge);
9/* Output:
10{
11 "25": [{ name: "Alice", age: 25 }, { name: "Charlie", age: 25 }],
12 "30": [{ name: "Bob", age: 30 }]
13}
14*/
15

These methods make managing and manipulating arrays of objects in JavaScript both efficient and straightforward.