Daniel Rodríguez
Daniel Rodríguez

Reputation: 23

Return Largest Number in Array using spread syntax

I'm trying to find the largest number in each sub array using this function:

/* jshint esversion: 6 */
function largestOfFour(arr) {
  var max=[];
  for(var i=0; i<arr.length; i++){
    for(var j=0; j<arr[i].length; j++){

     max.push(Math.max(...arr[j]));
    }

  }
  return max;

}

largestOfFour([[13, 27, 18, 26], [4, 5, 1, 3], [32, 35, 37, 39], [1000, 1001, 857, 1]]);

but when I run it, the result is, in fact, the largest numbers in each subarray, but repeated 4 times, like this:

[27,5,39,1001,27,5,39,1001,27,5,39,1001,27,5,39,1001]

and I'm not sure why. I would like to know what I'm doing wrong, thanks.

Upvotes: 1

Views: 119

Answers (3)

Redu
Redu

Reputation: 26191

You may also do recursively as follows in a Haskellesque pattern matching fashion;

function getLargests([x,...xs]){
  return [Math.max(...x)].concat(xs.length ? getLargests(xs) : []);
}

var arr = [[13, 27, 18, 26], [4, 5, 1, 3], [32, 35, 37, 39], [1000, 1001, 857, 1]];
console.log(getLargests(arr));

Upvotes: 0

Ori Drori
Ori Drori

Reputation: 192262

Array#map the array into the max of each sub array:

function largestOfFour(arr) {
  return arr.map((sub) => Math.max(...sub));
}

console.log(largestOfFour([[13, 27, 18, 26], [4, 5, 1, 3], [32, 35, 37, 39], [1000, 1001, 857, 1]]));

Upvotes: 0

Thai Doan
Thai Doan

Reputation: 292

You don't need the second loop:

    /* jshint esversion: 6 */
    function largestOfFour(arr) {
      var max=[];
      for(var i=0; i<arr.length; i++){
         max.push(Math.max(...arr[i]));
      }
      return max;
    }
    
    console.log(largestOfFour([[13, 27, 18, 26], [4, 5, 1, 3], [32, 35, 37, 39], [1000, 1001, 857, 1]]));

Upvotes: 2

Related Questions