-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"
  }
]
alextc
  • 3,206
  • 10
  • 63
  • 107

1 Answers1

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)
Code Maniac
  • 37,143
  • 5
  • 39
  • 60
Maksym Petrenko
  • 1,053
  • 1
  • 6
  • 15
  • `my_array.filter(function(item) { retrun [1,3,8].includes(item.id) })` Would work as well :) – Jonas Johansson Aug 12 '19 at 06:05
  • 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! – claasic Aug 12 '19 at 06:23