Cornwell
Cornwell

Reputation: 3410

IndexOf and .splice() equivalent for objects

I have the following code (jsfiddle):

var obj = {
    x: 48,
    y: 13
};
var main = [{
    x: 8,
    y: 3
}, {
    x: 82,
    y: 31
}, {
    x: 48,
    y: 13
}, {
    x: 28,
    y: 31
}];



var result = $.grep(main, function (e) {
    return ((e.x == obj.x) && (e.y == obj.y));
});

var index = main.indexOf(obj);
if (result.length > 0)
    main.splice(index, 1);

I understand it's an array of objects. Is there any other way besides iterating it myself to retrieve the index and then splice it?

Upvotes: 3

Views: 2682

Answers (3)

Christophe
Christophe

Reputation: 28114

Apparently what you are looking for is an associative array. You could rewrite your main array as an "associative array" (actually an object):

var main = {
    "8": {
        "3": {...}
    },
    "82": {
        "31": {...}
    },
// etc.
};

Then what you are looking for is simply:

main[obj.x][obj.y]

Upvotes: 0

basilikum
basilikum

Reputation: 10528

You actually already have the index. The callback of the $.grep() method takes as second argument the index. So you could write something like this:

var obj = {
    x: 48,
    y: 13
};
var main = [{
    x: 8,
    y: 3
}, {
    x: 82,
    y: 31
}, {
    x: 48,
    y: 13
}, {
    x: 28,
    y: 31
}];


var index;
var result = $.grep(main, function (e, i) {
    var res = (e.x == obj.x) && (e.y == obj.y);
    if (res) {
        index = i;
    }
    return res;
});

if (result.length > 0)
    main.splice(index, 1);

This will give you the last index, if there are multiple occurances. If you want the first index (as you would get it using indexOf on an array) you need to make sure that once index is set, it doesn't get overriden.

FIDDLE

Upvotes: 1

Bergi
Bergi

Reputation: 664307

var index = main.indexOf(obj);

The indexOf Array method does compare by equality, which for objects means their identity. You can only use it if your main array was like:

var main = [{x:8,y:3}, {x:82,y:31}, obj, {x:28,y:31}];
//                                  ^^^

Is there any other way besides iterating it myself to retrieve the index?

If you search for something that does not compare by equality, then no. Of course you can write a special helper function for that purpose (just like indexOf is one). Don't fear to do so (and you're not missing a native alternative)!

Upvotes: 1

Related Questions