0
let a =  [{
    a:1,
    b:3,
    c:[1, 2, 6]
    },
 {
    a:3,
    b:10,
    c:[2, 5, 4]
    },
 {
    a:4,
    b:3,
    c:[7, 12, 6]
    },
 {
    a:4,
    b:12,
    }]

let b = [2, 6]

I want to return an array from a object that matches from b arrays.

I used :

lodash.forEach(b , (value)=>{
   lodash.filter(a, {c: value})
}

but this doesnt work . I tried to simple my code for better underestanding.

Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
Babak Abadkheir
  • 2,222
  • 1
  • 19
  • 46

4 Answers4

1

You could filter the array by looking if the values of b are included in c.

var a = [{ a: 1, b: 3, c: [1, 2, 6] }, { a: 3, b: 10, c: [2, 5, 4] }, { a: 4, b: 3, c: [7, 12, 6] }, { a: 4, b: 12 }],
    b = [2, 6],
    result = a.filter(({ c = [] }) => b.some(v => c.includes(v)));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

For getting only items who match completely, you could use Array#every instead of Array#some.

var a = [{ a: 1, b: 3, c: [1, 2, 6] }, { a: 3, b: 10, c: [2, 5, 4] }, { a: 4, b: 3, c: [7, 12, 6] }, { a: 4, b: 12 }],
    b = [2, 6],
    result = a.filter(({ c = [] }) => b.every(v => c.includes(v)));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

To find objects with c contain all b values you can use Array.filter() and Array.every():

let a =  [{ a: 1, b: 3, c: [1, 2, 6] }, { a: 3, b: 10, c: [2, 5, 4] }, { a: 4, b: 3, c: [7, 12, 6] }, { a: 4, b: 12 }];

    let b = [2, 6]

    console.log(a.filter(({c = []}) => b.every(v => c.includes(v)))); 

if you want common values use Array.some() instead of Array.every():

let a =  [{ a: 1, b: 3, c: [1, 2, 6] }, { a: 3, b: 10, c: [2, 5, 4] }, { a: 4, b: 3, c: [7, 12, 6] }, { a: 4, b: 12 }];

        let b = [2, 6]

        console.log(a.filter(({c = []}) => b.some(v => c.includes(v)))); 
Fraction
  • 11,668
  • 5
  • 28
  • 48
0

Assuming you want to filter objects in array a that have atleast one value in c which exists in b array.

You can use Array.filter, Array.some & Array.includes

let a=[{a:1,b:3,c:[1,2,6]},{a:3,b:10,c:[2,5,4]},{a:4,b:3,c:[7,12,6]},{a:4,b:12,}];
let b=[2,6];

let result = a.filter(v => v.c && v.c.some(v1 => b.includes(v1)));
console.log(result);

You can use lodash as follows

let a=[{a:1,b:3,c:[1,2,6]},{a:3,b:10,c:[2,5,4]},{a:4,b:3,c:[7,12,6]},{a:4,b:12,}];
let b=[2,6];

let result = _.filter(a, v => v.c && _.some(v.c, c => _.includes(b,c)));
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
Nikhil Aggarwal
  • 28,197
  • 4
  • 43
  • 59
0

I believe this is what you want - you can do it in pure JS:

 

let a =  [{
a:1,
b:3,
c:[1, 2, 6]
},
 {
a:3,
b:10,
c:[2, 5, 4]
},
 {
a:4,
b:3,
c:[7, 12, 6]
},
 {
a:4,
b:12,
}]

let b = [2, 6]

let c = a.filter(({ c = [] }) => c ? b.some(n => c.includes(n))) : false;

console.log(c);
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79