1

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?

asked Jul 23, 2018 at 3:01

2 Answers 2

3

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.

answered Jul 23, 2018 at 3:05
Sign up to request clarification or add additional context in comments.

11 Comments

Thank you, I'm getting the number I need, but right after that there's console error "Uncaught TypeError: object2 is not a function". I'm working in React.
It looks like you're trying to call object2 as a function, but it's not a function, nor is it even a standalone variable - it's only a property of the accumulator
then how to call it properly to find the id of the object it is in?
Don't call it like a function, just access that property name, like in the snippet: indexedById.object2
in order to find the index, we create an object. This is not very efficient. Sorry, maybe I am missing something here.
|
2

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.

answered Jul 23, 2018 at 3:06

2 Comments

Thanks for the answer. Seems not working inside of a React function, and what is xs?
I added a note in my answer; xs would be the array you're searching through. You could also have the function take your array, like const findById = (x, xs) => xs.findIndex...etc.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.