简体   繁体   中英

Why doesn't my filter function work? (Javascript).

What I am trying to accomplish, being able to use the filter function to filter out the people that have the age: 21 and the color: blue.

Any suggestions on how to make it work? Thanks in advance.

Here is my code:

var arr = [   { name: 'Steve', age: 18, color: 'red' },   { name: 'Louis', age: 21, color: 'blue' },   { name: 'Mike', age: 20, color: 'green' },   { name: 'Greg', age: 21, color: 'blue' },   { name: 'Josh', age: 18, color: 'red' } ];

var filter = function(arr, criteria){
    var filtered = []
    for(var i=0; i<arr.length; i++){
        if (arr[i] === criteria) {
            filtered.push(arr[i])
        }
        return filtered; 
    }
     }

console.log(filter(arr, { age: 21, color: 'blue' }));

Cant compare object with ===

Testing objects equality in NodeJS

You should add return outside for-loop

var filter = function(arr, criteria){
    return arr.filter( function(item){
        return Object.keys(criteria).every(function(key) {
            return item[key] == criteria[key];
        });
    });
}

The reason your solution is not working is because you cannot compare two objects using the equality operator, so you have to actually compare the properties of the objects, use a library like lodash or underscore with a built in comparison functino, or write a deep equals function yourself that iterates through the properties of each and returns false if at any point they are not equal.

Here is one possible solution:

var filter = function(arr, criteria){
  var filtered = []
  arr.forEach(function (item) {
    if (item.age === criteria.age && item.color === criteria.color) {
      filtered.push(item);
    }
  });
  return filtered;
};

You'll have to loop over those Objects in your Array and test for their properties and property values. Here's a backward compatible way to do it:

function hasCompObjPropsAndVals(obj, compObj){
  var l = 0, c = 0;
  for(var i in compObj){
    l++;
    for(var p in obj){
      if(i === p && compObj[i] === obj[p]){
        c++;
        break;
      }
    }
  }
  if(l !== 0 && l === c){
    return true;
  }
  return false;
}
function filter(objArray, compObj){
  var res = [];
  for(var i=0,l=objArray.length; i<l; i++){
    var o = objArray[i];
    if(hasCompObjPropsAndVals(o, compObj)){
      res.push(o);
    }
  }
  return res;
}
var arr = [   { name: 'Steve', age: 18, color: 'red' },   { name: 'Louis', age: 21, color: 'blue' },   { name: 'Mike', age: 21, color: 'green' },   { name: 'Greg', age: 21, color: 'blue' },   { name: 'Josh', age: 18, color: 'red' } ];
console.log(filter(arr, {age: 21, color: 'blue'}));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM