Ruham
Ruham

Reputation: 759

Finding an array object ID by property

This may be a duplicate, but I'm not sure.

I have the following array:

[
  {
    id: "object1"
  },
  {
    id: "object2"
  },
  {
    id: "object3"
  }
]

The trick is, the array is dynamic, and, therefore, the global IDs of this array objects vary. For example, array[1] in one case may be an object with id "object1", and, in other case, that with an id of "object3".

How to query this array based on the id string and have the array index as the output?

Upvotes: 1

Views: 106

Answers (2)

Zac Anger
Zac Anger

Reputation: 7747

Array has a findIndex, so you could do const findById = (x) => xs.findIndex(({ id }) => id === x) where x is your id string and xs is your array of objects.

Upvotes: 2

CertainPerformance
CertainPerformance

Reputation: 370579

reduce into an object indexed by id, with the values being the index of that id's object in the original array, and then you can use simple object lookup:

const input = [
  {
    id: "object1"
  },
  {
    id: "object2"
  },
  {
    id: "object3"
  }
];
const indexedById = input.reduce((a, { id }, i) => {
  a[id] = i;
  return a;
}, {});
console.log(indexedById.object2); // index of 1 in input

.findIndex is another possibility, but it has worse time complexity than object lookup.

Upvotes: 3

Related Questions