-2

I have a JavaScript array of objects:

var my_array = [
  {
    "id" : 1,
    "aas_name" : "aaa"
  },
  {
    "id" : 2,
    "aas_name" : "bbb"
  },
  {
    "id" : 3,
    "aas_name" : "ccc"
  },
  ...
   ...
    ...
  ,
  {
    "id" : 10,
    "aas_name" : "jjj"
  }
]

I would like to find all objects in the my_array, each of which has the id value that exists in a pre-defined array [1, 3, 8] for instance without having to use the for... loop and ES6 arrow function style.

var result = [
  {
    "id" : 1,
    "aas_name" : "aaa"
  },
  {
    "id" : 3,
    "aas_name" : "ccc"
  },
  {
    "id" : 8,
    "aas_name" : "hhh"
  }
]
3
  • 4
    Use a .filter, var result = my_array.filter(function(item) { return [1,3,8].indexOf(item.id) != -1 }); Commented Aug 12, 2019 at 5:57
  • 1
    @MaksymPetrenko this should be posted as answer instead as comment mate :) Commented Aug 12, 2019 at 6:00
  • @CodeManiac posted it, thanks :) Commented Aug 12, 2019 at 6:03

1 Answer 1

6

Use a .filter:

The filter() method creates a new array with all elements that pass the test implemented by the provided function. filter

var my_array = [{"id": 1,"aas_name": "aaa"},{"id": 2,
"aas_name": "bbb"},{"id": 3,"aas_name": "ccc"},{"id": 8,"aas_name": "hhh"},{"id": 10,"aas_name": "jjj"}]

let result = my_array.filter(function(item) {
  return [1, 3, 8].indexOf(item.id) != -1;
});

console.log(result)

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

2 Comments

my_array.filter(function(item) { retrun [1,3,8].includes(item.id) }) Would work as well :)
For bigger data it would be more efficient to create a hashtable first and instead of indexOf do lookups on it. Instead of O(n * m) we'd have O(2 * n) (or O(3 * n)). This works well though!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.