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.

const users = [
{ name: "Alice", age: 25 },
{ name: "Bob", age: 30 },
{ name: "Charlie", age: 25 },
];
// Filter users by age
const age25Users = users.filter(user => user.age === 25);
console.log(age25Users); // [{ name: "Alice", age: 25 }, { name: "Charlie", age: 25 }]

2. Finding - find()

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

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

3. Mapping - map()

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

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

4. Sorting - sort()

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

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

5. Reducing - reduce()

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

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

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

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

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

const hasYoungUser = users.some(user => user.age < 30);
console.log(hasYoungUser); // true
const allUsersAreAdults = users.every(user => user.age >= 18);
console.log(allUsersAreAdults); // true

7. Grouping by Property

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

const groupedByAge = users.reduce((group, user) => {
const age = user.age;
if (!group[age]) group[age] = [];
group[age].push(user);
return group;
}, {});
console.log(groupedByAge);
/* Output:
{
"25": [{ name: "Alice", age: 25 }, { name: "Charlie", age: 25 }],
"30": [{ name: "Bob", age: 30 }]
}
*/

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