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] ]

Answer

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)