Wednesday, 4 January 2017

Javascript: Finding the index of an Object in an Array

Having done this more times than is wise it's documented here so that, when it's forgotten, this will act as an aide memoire.

Objects can be a bugger as they aren't equivalent unless they are actually the same thing:

console.log({"name": "Fred"} !== {"name": "Fred"});
var a = {"name": "Fred"};
var b = a;
console.log(a === b);

Meaning that the best way to check equivalence is to convert them to strings and compare them that way:

console.log(JSON.stringify({"name": "Fred"}) === JSON.stringify({"name": "Fred"}));

This string comparison is what happens in the following script. It iterates over the array of objects using the map array method and returns the index or false if the object does not exist in that position in the array. False values are filtered, and the array is counted. If the length is greater than zero then the index is again calculated and returned, otherwise -1 is returned.

var list = [
    {
        "name": "Jane"
    }, {
        "name": "John"
    }, {
        "name": "William"
    }],
    target = {
        "name": "Fred"
    },
    s = JSON.stringify,
    p = JSON.parse,
    c = a => p(s(a).replace(/(,false)/g, "").replace(/\[false\,/, "[").replace(/\,false\]/, "]").replace(/\[false\]/, "[]")),
    index = (c(list.map((o, i) => (s(o) === s(target)) && i)).length > 0) ? c(list.map((o, i) => (s(o) === s(target)) && i))[0] : -1;

console.log("index:", index);

It must be pointed out, though, that if the object is present more than once the index of the first appearance is returned.

The code is slightly tongue-in-cheek as it's stupidly minimal, please do take some time to check that you know what's going on before using it.

No comments:

Post a Comment