简体   繁体   中英

Filter javascript objects with another array

I have Javascript array of objets like this

var posts = [
 {area: 'NY', name: 'Bla', ads: true},
 {area: 'DF', name: 'SFS', ads: false},
 {area: 'TT', name: 'SDSD', ads: true},
 {area: 'SD', name: 'Engine', ads: false},
 {area: 'NSK', name: 'Toyota', ads: false},
];

and another filter collection like this

var filter = ['NY', 'SD'];

I am trying to filter my posts array with this filter

function filtered() {
  return posts
     .filter(function(post){
        return post.ads === true;
     })
     .filter(function(post){
        return filter.indexOf(post.area) > 0;
     })
}

console.log(filtered());

and this filter gives nothing, just empty array

Please check jsfiddle

There is only need single Array#filter method and the second condition should be indexOf(post.area) > -1; since index starts from 0 .

 var posts = [ {area: 'NY', name: 'Bla', ads: true}, {area: 'DF', name: 'SFS', ads: false}, {area: 'TT', name: 'SDSD', ads: true}, {area: 'SD', name: 'Engine', ads: false}, {area: 'NSK', name: 'Toyota', ads: false}, ]; var filter = ['NY', 'SD']; function filtered(p, f) { return p .filter(function(v) { return v.ads && f.indexOf(v.area) > -1; }) } console.log(filtered(posts, filter)); 

This is a typical use case for Array.prototype.filter() and Array.prototype.some() combo.

 var posts = [ {area: 'NY', name: 'Bla', ads: true}, {area: 'DF', name: 'SFS', ads: false}, {area: 'TT', name: 'SDSD', ads: true}, {area: 'SD', name: 'Engine', ads: false}, {area: 'NSK', name: 'Toyota', ads: false}, ], filter = ['NY', 'SD']; result = posts.filter(o => filter.some(f => o.ads && f === o.area)); console.log(result); // or with filter & includes combo result = posts.filter(o => o.ads && filter.includes(o.area)); console.log(result); 

You could use a more generic solution with constraints for filtering.

 function filter(array, constraints) { return array.filter(function(a) { return Object.keys(constraints).every(function(k) { return typeof constraints[k] === 'function' ? constraints[k](a[k]) : a[k] === constraints[k] ; }); }); } var posts = [{ area: 'NY', name: 'Bla', ads: true }, { rea: 'DF', name: 'SFS', ads: false }, { area: 'TT', name: 'SDSD', ads: true }, { rea: 'SD', name: 'Engine', ads: false }, { area: 'NSK', ame: 'Toyota', ads: false }], result = filter(posts, { ads: true, area: function (v) { return ['NY', 'SD'].indexOf(v) !== -1; } }); console.log(result); 

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