-2

I have an array of Objects:

[
    {id: 1, thing_id: 2},
    {id: 1, thing_id: 3},
    {id: 1, thing_id: 4}
]

and I want to filter that using an array of thing_ids:

[2,3]

I did look at filtering an array of objects using an array without nested loops js but it doesn't seem to work.

Clearly I need to use .filter somehow?

Mick

OliverRadini
  • 6,238
  • 1
  • 21
  • 46
Mick
  • 1,401
  • 4
  • 23
  • 40
  • 1
    `var newArray = arr.filter(a => thing_ids.includes(a.id))` – Satpal Jul 13 '18 at 12:06
  • Check [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) examples – cyberpirate92 Jul 13 '18 at 12:09
  • You can use underscore library for javascript (_.filter function ) Example :var array= [{id : 1 , id_thinng:2}, {id :1 , id_thing:3} ,{id:1, id_thing:4}]; var newArray = _.filter(array, function(test){ return test.id_thing == 2 || test.id_thing == 3 ; }); console.log(newArray); – Houssein Zouari Jul 13 '18 at 12:10
  • @HousseinZouari, Why do you need a library when things can be achieved using vanilla JS – Satpal Jul 13 '18 at 12:15

1 Answers1

0

You can make use of Array.prototype.filter() and Array.prototype.includes() like the following way:

var arr1 = [{ id:1, thing_id: 2},
{ id: 1, thing_id: 3},
{ id: 1, thing_id: 4}];

var arr2 = [2,3]

var res = arr1.filter(i => arr2.includes(i.thing_id))
console.log(res);
Mamun
  • 66,969
  • 9
  • 47
  • 59