0

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]

myTest532 myTest532
  • 2,091
  • 3
  • 35
  • 78
  • 1
    How are you wanting to identify the sub-array to remove? Sounds like you might want a combination of [`Array.prototype.findIndex()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex), [How to compare arrays in JavaScript?](https://stackoverflow.com/questions/7837456/how-to-compare-arrays-in-javascript) and [`Array.prototype.splice()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice) – Phil Jun 28 '20 at 23:29
  • That's in may problem. I don't know how to identify the subArray. – myTest532 myTest532 Jun 28 '20 at 23:36
  • Using the links above, you should be able to work it out. If you're still having trouble, please [edit your question](https://stackoverflow.com/posts/62629289/edit) to show what you tried and we should be able to help from there – Phil Jun 28 '20 at 23:37

1 Answers1

2

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);
blex
  • 24,941
  • 5
  • 39
  • 72
  • 1
    I like that this removes **all** the matching arrays, not just the first. – Phil Jun 28 '20 at 23:40
  • It's awesome. Thank you. Could you please explain the while(i--)? What's the condition to stop the loop? – myTest532 myTest532 Jun 28 '20 at 23:45
  • 1
    @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 it – blex Jun 28 '20 at 23:50