Home > other >  Math.max not filtering an array by highest number
Math.max not filtering an array by highest number

Time:01-31

I am trying to return an array containing the highest number of each nested array using the following code:

const triangles = [
      [6, 7, 10],
      [9, 3, 6],
      [6, 3, 5],
      [6, 13, 12],
      [7, 12, 8],
    ];

function test(triangles){
    return triangles.filter(triangle => Math.max(...triangle));
}

console.log(test(triangles));

It is not filtering anything and simply returning the same values back but I don't understand why.

CodePudding user response:

You need to map each (sides) array within the outer (triangles) array, to a max side.

const triangles = [
  [6,  7, 10],
  [9,  3,  6],
  [6,  3,  5],
  [6, 13, 12],
  [7, 12,  8],
];

const test = (triangles) => triangles.map(sides => Math.max(...sides));

console.log(test(triangles)); // [10, 9, 6, 13, 12]

  • Related