4

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

0

3 Answers 3

3

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.