0

Is there a built in Javascript function or library to do the following:

const data = [
    { name: 'name1', type: 'type1' },
    { name: 'name2', type: 'type2' },
    { name: 'name3', type: 'type3' },
    { name: 'name4', type: 'type2' },
];

To search the following and return all objects where type = 'type2'

Something similar to data.findIndex((i) => i.type === 'type2') but returns all matches rather than first index?

Thanks

Arthur
  • 2,622
  • 4
  • 28
  • 46
  • Possible duplicate of [Javascript: How to filter object array based on attributes?](https://stackoverflow.com/questions/2722159/javascript-how-to-filter-object-array-based-on-attributes) – Jibin Joseph Mar 22 '19 at 16:53

2 Answers2

9

You are looking for Array.filter():

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

Example:

const data = [
    { name: 'name1', type: 'type1' },
    { name: 'name2', type: 'type2' },
    { name: 'name3', type: 'type3' },
    { name: 'name4', type: 'type2' },
]

const result = data.filter(o => o.type === 'type2')

console.log(result)
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
1

You can use filter()

const data = [
    { name: 'name1', type: 'type1' },
    { name: 'name2', type: 'type2' },
    { name: 'name3', type: 'type3' },
    { name: 'name4', type: 'type2' },
];
let res = data.filter(({type}) => type === "type2");
console.log(res)
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73