badigard badigard - 4 months ago 12
JSON Question

Insert json object to ordered array in javascript

I have a array of ~2000 object like in this format:

[ {
"$order": 2998,
"text": "Rosales Glenn",
"id": 375
},
{
"$order": 2999,
"text": "Dillard Joyce",
"id": 450
},
{
"$order": 3000,
"text": "Maryellen Hogan",
"id": 365
},
{
"$order": 3002,
"text": "Jeannette Church",
"id": 207
}
]


I need to insert an object into the correct place in an efficient way:
e.g:

{
"$order": 3001,
"text": "Jeannette Chichi",
"id": 205
}


Assuming I don't need to overwrite an existing element (no duplicate "$order") when inserting the new one, anyone know a good and fast algorithm to insert the new object to the array using $order as the key?
external libraries are also an option (if they support Angular).
Thanks!

Answer

At least you need to iterate until the index is found.

var array = [{ "$order": 2998, "text": "Rosales Glenn", "id": 375 }, { "$order": 2999, "text": "Dillard Joyce", "id": 450 }, { "$order": 3000, "text": "Maryellen Hogan", "id": 365 }, { "$order": 3002, "text": "Jeannette Church", "id": 207 }],
    insert = { "$order": 3001, "text": "Jeannette Chichi", "id": 205 },
    index = -1;

array.some(function (a,i) {
    if (a.$order > insert.$order) {
        return true;
    }
    index = i;
});

array.splice(index + 1, 0, insert);

console.log(array);