Shahid Alam
Shahid Alam

Reputation: 41

using for loop instead of filter

Make a function that looks through an array of objects (first argument) and returns an array of all objects that have a 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.

this is a challenge is on freecodecamp and I am having difficulty writing a code for it using ONLY for loop. i can make it work with filter() and for loop but I want to see how it'll come out if we use if statement and for loop. can anyone please help me here?

Code:(using filter)

function whatIsInAName(collection, source) {
  // "What's in a name? that which we call a rose
  // By any other name would smell as sweet.”
  // -- by William Shakespeare, Romeo and Juliet
  var srcKeys = Object.keys(source);

  // filter the collection
  return collection.filter(function(obj) {
    for (var i = 0; i < srcKeys.length; i++) {
      if (
        !obj.hasOwnProperty(srcKeys[i]) ||
        obj[srcKeys[i]] !== source[srcKeys[i]]
      ) {
        return false;
      }
    }
    return true;
  });
}


//input
whatIsInAName([{ "apple": 1, "bat": 2 }, { "apple": 1 }, { "apple": 1, "bat": 2, "cookie": 2 }, { "bat":2 }], { "apple": 1, "bat": 2 })

//output
[{ "apple": 1, "bat": 2 }, { "apple": 1, "bat": 2, "cookie":2 }]

without using filter(my approach):

function whatIsInAName(collection, source) {
  let n=[]
  arrayOfSrc=Object.keys(source) // contains the array of properties of source
  for(let obj of collection){
    for(let propName of arrayOfSrc){
      //if obj hgas the property and the value of the property also matches
      if(obj.hasOwnProperty(propName) && source[propName]==obj[propName]){
        //push the matched object to n
       n.push(obj)
      }
    }
  }
  console.log(n)
return n
  
}

Upvotes: 0

Views: 350

Answers (1)

Kirill Savik
Kirill Savik

Reputation: 1278

Please use this code.

  let result=[]
  arrayOfSrc=Object.keys(source)
  for(let obj of collection){
    let count = 0;
    for(let propName of arrayOfSrc){
      if(obj.hasOwnProperty(propName) && source[propName]==obj[propName]){
        count++;
      }
    }
    if(result.indexOf(obj) == -1 && count == arrayOfSrc.length) result.push(obj)
  }
  return result

Upvotes: 1

Related Questions