Monday, January 16, 2017

A better way to search an Object in an Array

You can use the Array.prototype.map() to create a shadow array, which will help you search more fast, or furthermore you can create an index object like below, it will directly return the index you need.

var cars = [
    { id:23, make:'honda', color: 'green' },
    { id:36, make:'acura', color:'silver' },
    { id:18, make:'ford', color:'blue' },
    { id:62, make:'ford', color:'green' }, 
];
let cars_s = cars.map(function(x) {
    return x.id;
});
let i = cars_s.indexOf(18);
console.log(i); // 2
console.log(cars[i]); // { id:18, make:'ford', color:'blue' }

let index = {};
for (let i = 0; i < cars_s.length; i++) {
    index[cars_s[i]] = i;
}
console.log(index[18]); // 2

@reference_1_stackoverflow
 

No comments:

Post a Comment