0

i am trying to fetch into array of object.

i have : arrayOfObject :

0: {code: "YJYDWO1", route_id: 1}
1: {code: "YJYDWO2", route_id: 2}
2: {code: "YJYDWO3", route_id: 3}
3: {code: "YJYDWO4", route_id: 4}
4: {code: "YJYDWO5", route_id: 5}

I want to get object where route_id = 2 (example) using find or anything without for loop.

I do this using for loop:

for(let i=0; i<arrayOfObject.lenght; i++){
  if(arrayOfObjet[i].route_id == 2){
   // do what you want
}
}

that work but if i have 1 milion data object in arrayOfObject that take a large of time so i thing is better to do it using find or any method in javascript.

How to do this?

1
  • yes !, but i need other method like find hachset ... after some search hachset is more better for filter large data in small time. @Kinglish Commented Jul 2, 2021 at 6:47

1 Answer 1

2

You can use something like Array.find

let item = arrayOfObjects.find(x => x.route_id === 2)

But that is just hiding the for loop. Because iterating over the array is the only possibility to find the element.

To speed up the things a bit (if route_id are unique) you can break out of the loop once you found your element.

for (let element of arrayOfObject) {
  if (element.route_id === 2) {
    // Do your thing
    break;
  }
}

If you have to do many searches (and again route_id is unique) you probably should transform your array into a a map or something similar, so you can directly access the object by its key

// Do this once in the beginning
let m = new Map();
for (let e of arrayOfObject)
  m.set(e.route_id, e);


//Retrieve an element from the map
let x = m.get(2);
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.