-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

4
  • 1
    var newArray = arr.filter(a => thing_ids.includes(a.id)) Commented Jul 13, 2018 at 12:06
  • Check MDN examples Commented Jul 13, 2018 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); Commented Jul 13, 2018 at 12:10
  • @HousseinZouari, Why do you need a library when things can be achieved using vanilla JS Commented Jul 13, 2018 at 12:15

1 Answer 1

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

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.