How to use filter() and map() method In Javascript
The filter() method creates a new array with all elements that pass the test implemented by the provided function. The findProductsByID function first uses filter to filter out the IDs that exist in the productDetails object. Then, the map() is used to map the filtered IDs to their corresponding product details.
Example: Finding details of the products matching with ids in the array using the filter and map method.
Javascript
// Object with product IDs const productIDs = { ids: [101, 102, 104, 105] }; // Separate object containing product details const productDetails = { 101: { name: "Laptop" , price: 999 }, 102: { name: "Smartphone" , price: 599 }, 103: { name: "Headphones" , price: 99 }, 104: { name: "Tablet" , price: 299 }, 106: { name: "Mouse" , price: 29 } }; // Function to find products by // IDs using filter and map function findProductsByID(productIDs, productDetails) { return productIDs.ids .filter(id => productDetails .hasOwnProperty(id)) .map(id => productDetails[id]); } // Find products by IDs const matchingProducts = findProductsByID(productIDs, productDetails); console.log( "Matching products:" , matchingProducts); |
Matching products: [ { name: 'Laptop', price: 999 }, { name: 'Smartphone', price: 599 }, { name: 'Tablet', price: 299 } ]
How to find Objects Containing Matching Elements from Arrays in Another Object ?
The task is to find objects that contain matching elements from arrays in another object. An object containing an array of values and a separate object. The objective is to determine whether the values present in the array are also present as keys in the separate object.
These are the following methods:
Table of Content
- Using forEach loop
- Using filter() and map() method
- Using reduce() method