Created
April 14, 2022 17:52
-
-
Save jcolebot/3770aef60726a06c825124a911cec97d to your computer and use it in GitHub Desktop.
Matching Name and Value Pairs with Arguments
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Function looks through an array of objects and returns an array of all objects that have matching name and value pairs. | |
| // Each name and value pair of the source object has to be present in the object from the collection. | |
| // For example, if the first argument is [{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }]. | |
| // The second argument is { last: "Capulet" }. Then you must return the third object from the array (the first argument). | |
| // Because it contains the name and its value, that was passed on as the second argument. | |
| // Solution Using Filter and Every Methods | |
| function whatIsInAName(collection, source) { | |
| // Object.keys returns an array of property names. | |
| const solutionKey = Object.keys(source); | |
| // Filter array and check each element for matches. | |
| return collection | |
| .filter(obj => solutionKey | |
| .every(key => obj.hasOwnProperty(key) && obj[key] === source[key])); | |
| } | |
| // Solution Using For Loop | |
| function whatIsInAName(collection, source) { | |
| const sourceKeys = Object.keys(source); | |
| // filter the collection | |
| return collection.filter(obj => { | |
| for (let i = 0; i < sourceKeys.length; i++) { | |
| if (!obj.hasOwnProperty(sourceKeys[i]) || | |
| obj[sourceKeys[i]] !== source[sourceKeys[i]]) { | |
| return false; | |
| } | |
| } | |
| return true; | |
| }); | |
| } | |
| // Solution Using Reduce Method | |
| function whatIsInAName(collection, source) { | |
| const sourceKeys = Object.keys(source); | |
| // filter the collection | |
| return collection.filter(obj => sourceKeys | |
| .map(key => obj.hasOwnProperty(key) && obj[key] === source[key]) | |
| .reduce((a, b) => a && b)); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment