skip to Main Content

I have an array of arrays and I want to remove the 2nd element, i.e. index[1] from each of the inner arrays.

arrayOfArrays = [[80,60,40,17,19],[100,88,1234,99,12]];
var newArray = arrayOfArrays.forEach((array) => array.filter((value,index) => ![2,3].includes(index)));

However newArray is not getting populated, and arrayOfArrays is not getting changed. I cannot work out how to get it to work!

What I’m expecting (trying to achieve) is :

[[80,60,19],[100,88,12]]

3

Answers


  1. Use Array::map() instead of Array::forEach(), since forEach doesn’t create a new array, it just iterates it.

    arrayOfArrays = [[80,60,40,17,19],[100,88,1234,99,12]];
    var newArray = arrayOfArrays.map((array) => array.filter((value,index) => ![2,3].includes(index)));
    
    console.log(newArray);
    Login or Signup to reply.
  2. The issue with your current approach is that forEach does not return a new array; it simply executes a function on each element of the array. In your code, newArray is not getting populated because forEach doesn’t return anything (it implicitly returns undefined).
    use ‘map’ can slove that

    arrayOfArrays = [[80,60,40,17,19],[100,88,1234,99,12]];
    var newArray = arrayOfArrays.map(array => array.filter((_, index) => [2,3] !== index));
    console.log(newArray);
    
    Login or Signup to reply.
  3.     var arrayOfArrays = [[80,60,40,17,19],[100,88,1234,99,12]];
        var newArray = Array.from(arrayOfArrays, (array) => array.filter((value,index) => ![2,3].includes(index)));
        console.log(newArray);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search