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
-
1That's not a multi-D array, thats an array of objects, quite different :)tymeJV– tymeJV2013年10月31日 13:31:56 +00:00Commented Oct 31, 2013 at 13:31
-
take a look at the filter methodyoavmatchulsky– yoavmatchulsky2013年10月31日 13:33:09 +00:00Commented Oct 31, 2013 at 13:33
1 Answer 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.
Comments
Explore related questions
See similar questions with these tags.