

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
JavaScript in filter an associative array with another array
Suppose, we have two arrays of objects like these −
const data = [ {"XD_A":"XDL","XD_B_1":"38","XD_B_2":"PB"}, {"XD_A":"XDR","XD_B_1":"51","XD_B_2":"PB"}, {"XD_A":"XDL","XD_B_1":"58","XD_B_2":"PB"}, {"XD_A":"XDR","XD_B_1":"38","XD_B_2":"PB"}, {"XD_A":"XDL","XD_B_1":"76","XD_B_2":"PB"}, {"XD_A":"XDR","XD_B_1":"38","XD_B_2":"PB"} ]; const filters =[{"XD_A":"XDR"},{"XD_B_1":"38"}];
We are required to write a JavaScript function that takes in two such arrays as first and second argument respectively.
Then the function should pick only those objects from the first array (data array) that contains all those key-value pairs that exist in the second array (filter array).
And the function should shove all those objects into a new object and return that object.
For the above array, the returned array should contain exactly two objects like this −
const output = [ {"XD_A":"XDR","XD_B_1":"38","XD_B_2":"PB"}, {"XD_A":"XDR","XD_B_1":"38","XD_B_2":"PB"} ];
Example
The code for this will be −
const data = [ {"XD_A":"XDL","XD_B_1":"38","XD_B_2":"PB"}, {"XD_A":"XDR","XD_B_1":"51","XD_B_2":"PB"}, {"XD_A":"XDL","XD_B_1":"58","XD_B_2":"PB"}, {"XD_A":"XDR","XD_B_1":"38","XD_B_2":"PB"}, {"XD_A":"XDL","XD_B_1":"76","XD_B_2":"PB"}, {"XD_A":"XDR","XD_B_1":"38","XD_B_2":"PB"} ]; const filters =[{"XD_A":"XDR"},{"XD_B_1":"38"}]; const filter = (data, filters) => { return data.filter(e => { try{ filters.forEach(o => { Object.keys(o).forEach(key => { if(e[key] !== o[key]) throw new 1; }); }); return true; } catch(e){ return false; } }); } console.info(filter(data, filters));
Output
And the output in the console will be -
[ { XD_A: 'XDR', XD_B_1: '38', XD_B_2: 'PB' }, { XD_A: 'XDR', XD_B_1: '38', XD_B_2: 'PB' } ]
- Related Questions & Answers
- Filter one array with another array - JavaScript
- Filter JavaScript array of objects with another array
- Creating an associative array in JavaScript with push()?
- Filter array based on another array in JavaScript
- Creating an associative array in JavaScript?
- Filter an array containing objects based on another array containing objects in JavaScript
- How to filter an array from all elements of another array – JavaScript?
- Sorting an associative array in ascending order - JavaScript
- Filter array with filter() and includes() in JavaScript
- How to extend an existing JavaScript array with another array?
- Filter null from an array in JavaScript?
- Length of a JavaScript associative array?
- Modify an array based on another array JavaScript
- Filter an object based on an array JavaScript
- PHP Associative Array
Advertisements