Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to remove certain elements from the inner array in JavaScripts

var array = [[10, 20, 30, 20, 50], [40, 50, 60, 20, 20], [70, 80, 90, 20, 20], [70, 80, 90, 20, 20]];

For example i want to delete elements == 50

I want this result -> array= [[10,30,20], [40,60,20], [70,90,20], [70,90,20]];

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I try this solution but it is not working ->

  for (var i = 0; i < array.length; i++) {
    for (var j = 0; j < array[i].length; j++) {
      if (array[i][j] == 50) {
        array[i].splice(j, 1);
      }
    }
 }

>Solution :

You need to collect unwanted indices first and then return.

const
    data = [
        [10, 20, 30, 20, 50], 
        [40, 50, 60, 20, 20], 
        [70, 80, 90, 20, 20], 
        [70, 80, 90, 20, 20]
    ],
    //       ^^          ^^ cols with 50
    //
    indices = data.reduce(
        (r, a) => a.map((v, i) => v === 50 ? false : r[i] ?? true),
        []
    ),
    result = data.map(a => a.filter((_, i) => indices[i]));

result.forEach(a => console.log(...a));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading