0

hey guys so I'm trying to solve this problem here

Make a function that looks through a list (first argument) and returns an array of all objects that have equivalent property values (second argument).

but i can't seem to loop thru an array of objects if my life depended on it..... Here is my following code

function where(collection, source) {
  for(var prop in collection){
    if(collection.hasOwnProperty(prop)){
      console.log("collection." + prop + "=" + collection[prop]);
    }
  }
}

where([{ first: 'Romeo', last: 'Montague' }, { first: 'Mercutio', last: null }, { first: 'Tybalt', last: 'Capulet' }], { last: 'Capulet' });

i was reading documents on hasOwnProperty method and for in loops but it seems like I am utilizing them wrong, any guidance is appreciated, thanks.

THIS IS NOT A DUPLICATE

hello world
  • 1,727
  • 6
  • 21
  • 37

2 Answers2

1

The for...in loop is not what you want for iterating over arrays in javascript.

Use the sequential for loop to loop through the array, and the for..in loop to iterate over the keys of the object...

for(var i=0; i<collections.length; i+=1) {
  for(var prop in collections[i]){
    if(collections[i].hasOwnProperty(prop)){
      console.log("collection." + prop + "=" + collections[i][prop]);
    }
  }
}
Community
  • 1
  • 1
sfletche
  • 47,248
  • 30
  • 103
  • 119
1

One can use filter method to filter out elements that satisfy the condition. Also, since comparison of objects is needed in evaluating the condition, and there does not seem to be an equals method in JavaScript for Objects, one has to do additional work to check equality.

Here is one way the problem mentioned in question can be solved

function where(collection, source) {
  return collection.filter(function(item) { 
     return Object.keys(source).every(function(k){ return item[k] == source[k] });
  });
}

console.log (where([{ first: 'Romeo', last: 'Montague' }, { first: 'Mercutio', last: null }, { first: 'Tybalt', last: 'Capulet' }], { last: 'Capulet'}));

Output

[ { first: 'Tybalt', last: 'Capulet' } ]
Wand Maker
  • 18,476
  • 8
  • 53
  • 87