-1

Is there a way to remove an array from a nested array in JavaScript?

I have the following array:

arr = [
    [1, 2],
    [2, 3],
    [3, 4]
]

and I want to remove the value [2, 3] from the array so that it results with:

arr = [
    [1, 2],
    [3, 4]
]

I have already tried the answers on How can I remove a specific item from an array?, but they don't seem to work. I was wondering if there was a fast efficient way of doing this.

Edit:

I already tried using indexOf and findIndex, and it does not return the index of an array inside of the array.

arr = [
  [1, 2],
  [2, 3],
  [3, 4]
];
console.log(arr.indexOf([2, 3]));
console.log(arr.findIndex([2, 3]));

This did not work, even though it was suggested in the comments below.

Furthermore, using:

console.log(arr.filter(nested => nested[0] !== 2 || nested[1] !== 3));

will be inefficient as in my code I need to remove large lists, which have hundreds of values, I only provided an example in my question.

Any help would be appreciated.

  • *"...but they don't seem to work."* Yes, they do. For instance, the [`filter` answer](https://stackoverflow.com/a/12952256/157247): `arr = arr.filter(nested => nested[0] !== 2 || nested[1] !== 3)`. Or `findIndex` followed by `splice`. Or... – T.J. Crowder Oct 25 '21 at 11:16
  • _"but they don't seem to work"_ - I am _guessing_ that's probably due to you not taking into account how Array.indexOf works. Since you have not shown any actual code of your own attempts, guess is all we can do here. – CBroe Oct 25 '21 at 11:16
  • @T.J.Crowder, thank you for your suggestions, but I have already tried what you both have suggested, and they do not seem to work. Thanks anyway for attempting to help. – sasindumaheepala Oct 25 '21 at 11:50
  • @CBroe, thank you for your suggestions, but I have already tried what you both have suggested, and they do not seem to work. Thanks anyway for attempting to help. – sasindumaheepala Oct 25 '21 at 11:50
  • @sasindumaheepala - Look at the documentation of `findIndex`, you're just not using it correctly. Also beware that `[2, 3] === [2, 3]` is always false, no array is `===` another array. So `indexOf([2, 3])` will **always** return -1. – T.J. Crowder Oct 25 '21 at 11:52

1 Answers1

1

var arr = [
    [1, 2],
    [2, 3],
    [3, 4]
]
console.log('Before =>', arr);
arr.splice(1, 1); // .splice(index, 1);
console.log('After=>', arr);
Ravi Ashara
  • 1,177
  • 7
  • 16