Deleting specific array element from multidimensional array?
11,177
Solution 1
var myArray = [["Tom", "161"], ["Dick", "29"], ["Harry", "46"]];
var myNewArray = myArray.filter(function(item){ return item[1] != 29 })
.filter uses native code to loop over your array. Building a new array could of course be more expensive than just cutting a part out of the old one, to be tested.
Solution 2
myArray = [["Tom", "161"], ["Dick", "29"], ["Harry", "46"]];
for(var i = 0; i <= myArray.length - 1; i++){
if(myArray[i][1] == "29"){
myArray[i].splice(0,2);
}
}
console.log(myArray);
// returns [ [ 'Tom', '161' ], [], [ 'Harry', '46' ] ]
Related videos on Youtube
Author by
aadu
Updated on September 26, 2022Comments
-
aadu over 1 year
I'm having trouble cycling through a multidimensional array and deleting a specific element array. My multidimensional array looks a little like this:
myArray = [["Tom", "161"], ["Dick", "29"], ["Harry", "46"]];
So if I have the number 29. What's the most efficient way to cycle through this array and delete the array element who's second element is 29? i.e. ["Dick", "29"]
-
aadu almost 11 yearsThat works, but you think making a new array is less efficient than the above loop and splice method?
-
brbcoding almost 11 yearsThis method is substanially faster than mine... jsperf.com/removearrfrommulti