![]() |
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 loopThe forEach executes a provided function once for each array element. It does not return a new array. It is used to iterate through each ID in productIDs.ids and check if it exists in the productDetails object, pushing the corresponding product details into the matchingProducts array. Example: Finding details of the products matching with IDs in the array using the forEach. Javascript
Output
Matching products: [ { name: 'Laptop', price: 999 }, { name: 'Smartphone', price: 599 }, { name: 'Tablet', price: 299 } ] Using filter() and map() methodThe 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
Output
Matching products: [ { name: 'Laptop', price: 999 }, { name: 'Smartphone', price: 599 }, { name: 'Tablet', price: 299 } ] Using reduce() methodThe reduce() method is used to accumulate the matching products. It iterates over each ID in the productIDs.ids array and checks if the ID exists in the productDetails object. If it does, it adds the corresponding product details to the accumulator (matchingProducts). Example: Fnding details of the products matching with ids in the array using the reduce method. Javascript
Output
Matching products: [ { name: 'Laptop', price: 999 }, { name: 'Smartphone', price: 599 }, { name: 'Tablet', price: 299 } ] |
Reffered: https://www.geeksforgeeks.org
JavaScript |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 14 |