3

I have list

var list = [
  {name: 'Hello', ads: true, pas: ['Av', 'Sd', 'Qr']},
  {name: 'Fre', ads: false, pas: ['Sd', 'Bc']},
  {name: 'Nat', ads: false, pas: ['Bc', 'Mo', 'Rr']},
  {name: 'Bor', ads: true, pas: ['Bo', 'Be', 'De']},
  {name: 'Arg', ads: true, pas: ['Ar', 'Na', 'Br']},
];

and filter of array

var filter = [
 'Sd','Be'
];

I have tried with filter but its not filtering.

list
  .filter(function(ls) {
    return ls.pas
      .filter(function(p){
        return filter.indexOf(p) > -1;
      })
  })

My expected output

[
  {name: 'Hello', ads: true, pas: ['Av', 'Sd', 'Qr']},
  {name: 'Fre', ads: false, pas: ['Sd', 'Bc']},
  {name: 'Bor', ads: true, pas: ['Bo', 'Be', 'De']}
];
4
  • Use $.inArray() Commented Oct 17, 2016 at 11:41
  • i cant use jquery, its inside react, but i can use lodash, but i don't know how to use it. Commented Oct 17, 2016 at 11:41
  • why does the answer of the last question of you does not work for you? Commented Oct 17, 2016 at 11:42
  • last question only got one level of filtering, this collection contains multiple levels of array to be filter. Commented Oct 17, 2016 at 11:43

2 Answers 2

3

You can use some() to check if any element from pas array of current object is inside filter array.

var list = [
  {name: 'Hello', ads: true, pas: ['Av', 'Sd', 'Qr']},
  {name: 'Fre', ads: false, pas: ['Sd', 'Bc']},
  {name: 'Nat', ads: false, pas: ['Bc', 'Mo', 'Rr']},
  {name: 'Bor', ads: true, pas: ['Bo', 'Be', 'De']},
  {name: 'Arg', ads: true, pas: ['Ar', 'Na', 'Br']},
];

var filter = [
 'Sd','Be'
];

var result = list.filter(function(e) {
  return e.pas.some(function(a) {
    return filter.indexOf(a) != -1
  })
})

console.log(result);

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

Comments

0

Using es6 it looks quite nice:

const list = [
   {name: 'Hello', ads: true, pas: ['Av', 'Sd', 'Qr']},
   {name: 'Fre', ads: false, pas: ['Sd', 'Bc']},
   {name: 'Nat', ads: false, pas: ['Bc', 'Mo', 'Rr']},
   {name: 'Bor', ads: true, pas: ['Bo', 'Be', 'De']},
   {name: 'Arg', ads: true, pas: ['Ar', 'Na', 'Br']},
],
filter = ['Sd','Be']

list.filter(a=>a.pas.some(a=>filter.includes(a))

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.