Skip to content Skip to sidebar Skip to footer

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}, {a

Solution 1:

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'];

functionfiltered(p, f) {
  return p
    .filter(function(v) {
      return v.ads && f.indexOf(v.area) > -1;
    })
}

console.log(filtered(posts, filter));

Solution 2:

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);

Solution 3:

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

functionfilter(array, constraints) {
    return array.filter(function(a) {
        returnObject.keys(constraints).every(function(k) {
            returntypeof 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);

Post a Comment for "Filter Javascript Objects With Another Array"