-1

How to find all the data of object by given id. For example this is my array of obbject:

const array = [{
    "name": "max",
    "id": 10
  },

  {
    "name": "ram",
    "id": 20
  },

  {
    "name": "sita",
    "id": 30
  },

  {
    "name": "bill",
    "id": 10
  },
]

Now i wanna create function that returns all data that has id of 10. The function should return, {"name": "max", "id": 10} and {"name": "bill", "id": 10}.

I tried doing this:

const array = [{
    "name": "max",
    "id": 10
  },

  {
    "name": "ram",
    "id": 20
  },

  {
    "name": "sita",
    "id": 30
  },

  {
    "name": "bill",
    "id": 10
  },
]

function findData(data, id) {
  const found = data.find(element => element.id === id)
  return found
}

console.log(findData(array, 10))

but the problem is, it just returns one object instead of returning all the data

ibrahim mahrir
  • 31,174
  • 5
  • 48
  • 73
DjBillje Official
  • 246
  • 1
  • 4
  • 14

2 Answers2

1

Use Array.filter()

const array = [
  { name: 'max', id: 10 },

  { name: 'ram', id: 20 },

  { name: 'sita', id: 30 },

  { name: 'bill', id: 10 }
];

function findData(data, id) {
  return data.filter(element => element.id === id);
}

console.log(findData(array, 10));
michael
  • 4,053
  • 2
  • 12
  • 31
wangdev87
  • 8,611
  • 3
  • 8
  • 31
0

you could use Array#filter instead of Array#find

const array = [ {"name": "max", "id": 10 }, {"name": "ram", "id": 20 }, {"name": "sita", "id": 30 }, {"name": "bill", "id": 10 }, ]

function findData(data, id){
    const found = data.filter(element => element.id === id)
    return found
}

console.log(findData(array, 10))
prasanth
  • 22,145
  • 4
  • 29
  • 53