Charabon
Charabon

Reputation: 787

Removing element from multidimensional array in Javascript

I am attempting to remove an element from a multidimensional array in javascript, the array is built like this:

selectedClients.push({client: id, package: package_id, transfer: transfer_id});

However there can be multiple clients, in multiple packages in multiple transfers in this array, how could I remove an element from this array using all three identifiers rather than just one?

for example:

Array[0]
{
client: 1
package: 1
transfer: 1
}
Array[1]
{
client: 2
package: 1
transfer: 1
}
Array[2]
{
client: 1
package: 2
transfer: 2
}

Many Thanks

Upvotes: 1

Views: 1644

Answers (1)

tymeJV
tymeJV

Reputation: 104775

You can roll your own function, that will take in an object with the exact amount of properties as the ones in your array, and then slice out the object it finds:

Say you pass in:

{client: 1, package: 1, transfer: 1}

Lets build!

//Returns the new array if found, false if nothing
function removeObjectFromArray(objectToRemove, arrayOfObjects) {
    for (var i = 0; i < arrayOfObjects.length; i++) {
        var stringyArrObj       = JSON.stringify(arrayOfObjects[i]),
            stringyRemoveObject = JSON.stringify(objectToRemove);

            if (stringyArrObj === stringyRemoveObject)
                return arrayOfObjects.slice(i, i+1);
    }
return false; 
}

Order of the object IS IMPORTANT, as stringify wont match up if the objects aren't ordered the same way. If that's an issue, you'll have to write a bit of a larger function comparing the keys individually.

Upvotes: 1

Related Questions