K
K
Kusmich2017-03-16 15:43:29
JavaScript
Kusmich, 2017-03-16 15:43:29

How to sort an array of objects for binary search?

There is an array of objects (there are a lot of objects), you need to sort them so that binary search can be applied.

obj = [
       12234 :{
                "ID" : "CV122H32",
                "name"     :  "Дмитрий",
                "position" :  "Слесарь"  
        },
               334534:{
                "ID" : "SM12345",
                "name"     :  "Антон",
                "position" :  "Електрик"  
        },
    ]


For example, in the object above, you need to use the search for a person by the id field. But since the array of objects is very large, you need to somehow optimize the search.

I read that a good option is "binary search". But before using it, you need to use sorting. Here the moment from sorting is not clear to me.
What sorting should be used specifically for my case?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
G
GavriKos, 2017-03-16
@Kusmich

Any. The main thing is that the array should be sorted in ascending order according to the parameter by which the search will be carried out.
But, if there are a lot of objects (millions) - then this approach is not correct - it's better to have a database then.

E
Eugene, 2017-03-16
@AppFA

The code you provided is not valid, you are trying to add a key to the array, there are no associative arrays in JS, but you can use objects as a hash table:

const data = {
    12234: { ... },
    334534: { ... }
};

In this situation, you do not need to sort and do anything, just take data from the hash table according to the key you need:
PS If your data initially comes in the form of an array of objects, i.e.:
const data = [
    { ... },
    { ... }
];

You should normalize the data and bring it to the form that I wrote above, as an option in JS there is either for this: "normalizr"

K
Kuraudo, 2017-03-16
@Kuraudo

lodash method _.sortBy(obj, 'ID').

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question