Advertisement
Guest User

Untitled

a guest
Jun 18th, 2019
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.33 KB | None | 0 0
  1. //Make a function that looks through an array of objects (first argument) and returns an array of all objects that have matching name and value pairs (second argument). Each name and value pair of the source object has to be present in the object from the collection if it is to be included in the returned array.
  2.  
  3. function whatIsInAName(collection, source) {
  4. // New array (for filtering
  5. var arr = [];
  6. // Convert the key(s) of the source object into an array.
  7. let src = Object.keys(source);
  8. // Filter the collection array.
  9. arr = collection.filter(function(obj){
  10. // Loop through the elements of the src array.
  11. for (let i = 0; i < src.length; i++){
  12. // If a collection object does not have a property matching the src array element OR the value of the matching collection object's property does not match the source property of the same name/key
  13. if (obj.hasOwnProperty(src[i]) === false || obj[src[i]] !== source[src[i]]){
  14. // Do not inclue this object in the filtered array.
  15. return false;
  16. }
  17. }
  18. // Otherwise, include the object in the filtered array.
  19. return obj;
  20. })
  21. // Return the filtered array.
  22. return arr;
  23. }
  24.  
  25. whatIsInAName([{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }], { last: "Capulet" });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement