I know it might be a stupid question, but I didn't find any solution for it.
For example, if I have the arr1 = [[1,2,3], [1,2,2], [4,3]] and I want to remove the subarray [1,2,2]. Is it possible in Javascript?
The result should be: [[1,2,3],[4,3]]. Also, if I try to remove [0,1,2], nothing happens because the arr1 does not have the subarray [0,1,2]
asked Jun 28, 2020 at 23:27
myTest532 myTest532
2,4037 gold badges43 silver badges100 bronze badges
1 Answer 1
You could use splice to remove arrays of the same length which have the exact same elements:
function removeSubArray(source, sub) {
let i = source.length;
while(i--) {
if (source[i].length === sub.length && sub.every((n, j) => n === source[i][j])) {
source.splice(i, 1);
}
}
}
const arr1 = [[1,2,3], [1,2,2], [4,3]];
const arr2 = [1,2,2];
removeSubArray(arr1, arr2);
console.log(arr1);
answered Jun 28, 2020 at 23:34
blex
25.7k6 gold badges49 silver badges78 bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
Phil
I like that this removes all the matching arrays, not just the first.
myTest532 myTest532
It's awesome. Thank you. Could you please explain the while(i--)? What's the condition to stop the loop?
blex
@myTest532myTest532 I'm doing
i-- because I'm going backwards, from right to left. This is practical, because when splicing, we are removing elements, so we would have to use some hacks to keep i consistent when going from left to right. As for the stop, that will happen when i is equal to 0, because 0 is a falsy value. i-- returns the current value of i, and then subtracts 1 from itlang-js
Array.prototype.findIndex(), How to compare arrays in JavaScript? andArray.prototype.splice()