'Write a function to identify objects in the first array, which matches all the attribute and value pairs in the second object

Return type should be a array.


findMatches(
    [
        {"X" : "1", "Y" : "2","Z" : "4", "P" : "5"},
        {"X" : "2", "Y" : "2","Z" : "4", "P" : "5"},
        {"X" : "1", "Y" : "2","Z" : "9", "P" : "6"}
    ],
    {"X":"1", "Y":"2"}
);

Should return

[
    {"X" : "1", "Y" : "2","Z" : "4", "P" : "5"}, 
    {"X" : "1", "Y" : "2","Z" : "9", "P" : "6"}
]

Answer should be valid for any given input.

function findMatches(arr ,obj) {
    return [];
}
findMatches(
    [
        {"X" : "1", "Y" : "2","Z" : "4", "P" : "5"}, 
        {"X" : "2", "Y" : "2","Z" : "4", "P" : "5"}, 
        {"X" : "1", "Y" : "2","Z" : "9", "P" : "6"}
    ], 
    {"X":"1", "Y":"2"}
);



Solution 1:[1]

You can simply achieve it by using Array.filter() method.

Demo :

const arr = [
  {"X" : "1", "Y" : "2","Z" : "4", "P" : "5"},
  {"X" : "2", "Y" : "2","Z" : "4", "P" : "5"},
  {"X" : "1", "Y" : "2","Z" : "9", "P" : "6"}
];

const obj = {"X":"1", "Y":"2"};

function findMatches(arr, obj) {
   return arr.filter((arrayObj) => (arrayObj.X === obj.X) && (arrayObj.Y === obj.Y));
}

const res = findMatches(arr, obj);

console.log(res);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Rohìt Jíndal