JavaScript in filter an associative array with another array

In this article, we'll explore how to filter an associative array using another array in JavaScript. This is a common task when you need to extract specific objects from a dataset based on matching criteria.

What is an Associative Array?

An associative array is a data structure that stores key-value pairs. Each key is associated with a specific value and serves as a unique identifier. Unlike regular arrays, associative arrays don't use numeric indexes?keys can be strings or numbers.

In JavaScript, objects function as associative arrays since they store key-value pairs where keys can be strings or symbols:

const customer = {
   name: 'Rishi',
   age: 25,
   city: 'Mumbai'
};

Using filter() and includes() Methods

The most straightforward approach combines the filter() method with includes(). We create a filter criteria array and use it to match against specific properties in our data array.

Example

// Define data with name and age
const data = [
   { name: 'Anita', age: 45 },
   { name: 'Tanvi', age: 20 },
   { name: 'Bittu', age: 32 }
];

// Filter data based on names
const filterCriteria = ['Anita', 'Bittu'];
const filteredData = data.filter(item => filterCriteria.includes(item.name));

console.log(filteredData);
[ { name: 'Anita', age: 45 }, { name: 'Bittu', age: 32 } ]

Complexity

Time complexity: O(n × m) where n is the data array length and m is the filter criteria length. Space complexity: O(k) where k is the number of matching elements.

Using filter() and some() Methods

This approach uses filter() with the some() method. The some() method tests whether at least one element in an array passes a given condition, making it useful for more flexible filtering scenarios.

Example

// Define an associative array
const data = [
   { name: 'Anita', age: 45 },
   { name: 'Tanvi', age: 20 },
   { name: 'Bittu', age: 32 }
];

// Define the array to filter with
const filterCriteria = [20, 45]; 

// Filter the associative array by age
const filteredData = data.filter(item => 
   filterCriteria.some(age => age === item.age)
);

console.log(filteredData);
[ { name: 'Anita', age: 45 }, { name: 'Tanvi', age: 20 } ]

Complexity

Time complexity: O(n × m) where n is the data array length and m is the filter criteria length. Space complexity: O(k) for the filtered results.

Comparison of Methods

Method Best For Readability Performance
filter() + includes() Simple property matching High Good for small arrays
filter() + some() Complex conditions Medium More flexible

Conclusion

Both approaches effectively filter associative arrays using another array as criteria. Use filter() with includes() for simple matching, and filter() with some() for more complex filtering conditions.

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

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements