Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get unflattened filtered Multidimensional Array in Javascript

I am able to filter the elements of matrix W to elements that satisfy the conditional statement => keep elements in each inner matrix that is below the median value. The elements of the median array are the median values for each inner array.

const W = [[45, 60, 15, 35],[45, 55, 75],[12, 34, 80, 65, 90]
];
const median = [ 40, 55, 65 ];
const Wmin = [];
for (let j = 0; j < W.length; j++) {
    for (let k = 0; k < W[j].length; k++) {
        if (W[j][k] < median[j]) {
            Wmin.push(W[j][k]);
        }
    }
}


console.log(Wmin)

I used a for-loop, but the resulting Wmin array is flattened. My goal is to be able to filter W and still get unflattened 2D array.

I am getting Wmin = [ 15, 35, 45, 12, 34 ], but the expected array should be Wmin = [ [15, 35], [45], [12, 34] ]

like image 270
Isaac Avatar asked Feb 23 '19 06:02

Isaac


2 Answers

You can use map and filter

const W = [[45, 60, 15, 35],[45, 55, 75],[12, 34, 80, 65, 90]];
const median = [ 40, 55, 65 ];

const op = W.map(( inp, index) => inp.filter(e => e < median[index]))

console.log(op)

Why my code is not working

You're pushing values directly into array inside inner for loop, you need to create a temporary array and push value in it in inner loop and push the temporary to Wmin in outer loop

const W = [[45, 60, 15, 35],[45, 55, 75],[12, 34, 80, 65, 90]];
const median = [ 40, 55, 65 ];
const Wmin = [];
   for (let j = 0; j < W.length; j++) {
     let temp = []
      for (let k = 0; k < W[j].length; k++) {
         if (W[j][k] < median[j]) {
            temp.push(W[j][k]);
         }
     }
  Wmin.push(temp)
}

console.log(Wmin)
like image 154
Code Maniac Avatar answered Nov 05 '22 19:11

Code Maniac


Another alternative to solve this problem could be making a copy of the original array with Array.slice() and then iterate over the elements of this copy deleting the numbers that don't meet the condition (i.e are greater or equal to the median) with Array.splice().

const W = [[45, 60, 15, 35],[45, 55, 75],[12, 34, 80, 65, 90]];
const median = [40, 55, 65];

// Clone the original array.

let Wmin = W.slice();

// Delete elements from the cloned array.

for (let j = 0; j < Wmin.length; j++)
{
    for (let k = 0; k < Wmin[j].length; k++)
    {
        if (Wmin[j][k] >= median[j])
        {
            Wmin[j].splice(k, 1);
            --k;
        }
    }
}

console.log(Wmin);

Or, if you like, you can approach this with Array.reduce() and Array.filter() too:

const W = [[45, 60, 15, 35],[45, 55, 75],[12, 34, 80, 65, 90]];
const median = [40, 55, 65];

let Wmin = W.reduce(
    (acc, arr, i) => (acc.push(arr.filter(x => x < median[i])) && acc),
    []
);

console.log(Wmin);
like image 34
Shidersz Avatar answered Nov 05 '22 21:11

Shidersz