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]

3
  • 1
    How are you wanting to identify the sub-array to remove? Sounds like you might want a combination of Array.prototype.findIndex(), How to compare arrays in JavaScript? and Array.prototype.splice() Commented Jun 28, 2020 at 23:29
  • That's in may problem. I don't know how to identify the subArray. Commented Jun 28, 2020 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 to show what you tried and we should be able to help from there Commented Jun 28, 2020 at 23:37

1 Answer 1

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);

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

3 Comments

I like that this removes all the matching arrays, not just the first.
It's awesome. Thank you. Could you please explain the while(i--)? What's the condition to stop the loop?
@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

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.