Filtering array of objects in JavaScript

Filtering arrays of objects is a common task in JavaScript. This article shows how to filter an array of objects based on values from another array using the filter() and includes() methods.

Problem Statement

Suppose we have two arrays - one containing literal values and another containing objects:

const source = [1, 2, 3, 4, 5];
const cities = [{ city: 4 }, { city: 6 }, { city: 8 }];

console.log("Source array:", source);
console.log("Cities array:", cities);
Source array: [1, 2, 3, 4, 5]
Cities array: [{ city: 4 }, { city: 6 }, { city: 8 }]

We need to create a new array containing only those objects whose "city" property value exists in the source array.

Using filter() and includes()

The filter() method creates a new array with elements that pass a test. Combined with includes(), we can check if object values exist in another array:

const source = [1, 2, 3, 4, 5];
const cities = [{ city: 4 }, { city: 6 }, { city: 8 }];

const filterByLiterals = (objArr, literalArr) => {
    const common = objArr.filter(el => {
        return literalArr.includes(el['city']);
    });
    return common;
};

console.log(filterByLiterals(cities, source));
[{ city: 4 }]

Simplified Version

We can make the function more concise using arrow function syntax:

const source = [1, 2, 3, 4, 5];
const cities = [{ city: 4 }, { city: 6 }, { city: 8 }];

const filterByLiterals = (objArr, literalArr) => 
    objArr.filter(el => literalArr.includes(el.city));

console.log(filterByLiterals(cities, source));
[{ city: 4 }]

Multiple Properties Example

This approach works with objects containing multiple properties:

const validIds = [101, 103, 105];
const users = [
    { id: 101, name: "Alice", age: 25 },
    { id: 102, name: "Bob", age: 30 },
    { id: 103, name: "Charlie", age: 35 }
];

const activeUsers = users.filter(user => validIds.includes(user.id));
console.log(activeUsers);
[
  { id: 101, name: 'Alice', age: 25 },
  { id: 103, name: 'Charlie', age: 35 }
]

How It Works

  1. filter() iterates through each object in the array
  2. For each object, it checks if the specified property value exists in the reference array
  3. includes() returns true if the value is found, false otherwise
  4. Only objects that return true are included in the new array

Conclusion

Combining filter() and includes() provides an efficient way to filter arrays of objects based on values from another array. This pattern is useful for data filtering and validation tasks in JavaScript applications.

Updated on: 2026-03-15T23:19:00+05:30

855 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements