1

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

2
  • 1
    That's not a multi-D array, thats an array of objects, quite different :) Commented Oct 31, 2013 at 13:31
  • take a look at the filter method Commented Oct 31, 2013 at 13:33

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.