Bryon Miller
Bryon Miller

Reputation: 11

JavaScript: Return largest number

Can someone tell me what is wrong with this code? I am trying to return the largest numbers from four separate arrays.

function largestOfFour(arr) {
  var longList = [];
  for (var i in arr){
    var longest = 0;
    for (var x=0; x<i.length; x++){
      if (i[x] > longest){
        longest=i[x];
      }
      longList.push(longest);
    }
  }
  return longList;
}

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

EDIT: Lye Fish provided the answer below. Here is the new code:

function largestOfFour(arr) {
  return arr.map(Function.apply.bind(Math.max, Math));
}

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

Upvotes: 0

Views: 188

Answers (2)

webdeb
webdeb

Reputation: 13211

// sort function
var op = function(a, b) { return a < b};

// the input
arr2d = [[8,7,1,78,899],[8,7,1,78,198],[8,7,1,78,598],[8,7,1,78,398]]; 
// output
var result = [];
// process
arr2d.forEach(function(arr) {
   result.push(arr.sort(op)[0]); // sort and return the highest of the numbers
});

Upvotes: 0

Amadan
Amadan

Reputation: 198324

for(var i in arr) gives indices, so i[x] ends up being 0[0] instead of being arr[0][0].

Use for (var index=0; index<arr.length; index++) { i = array[index]; ... }, or (unless you are supporting the ancients) Array.each, for iterating through array items (or better yet, Array.reduce):

var arrayMax = function(arr) {
  return arr.reduce(function(a, e) { return Math.max(a, e); });
}
arrayMax(arr.map(arrayMax));
// ==> 1001

Or, better yet:

var arrayMax = function(arr) {
  return Math.max.apply(Math, arr);
}
arrayMax(arr.map(arrayMax));
// ==> 1001

EDIT: It might be I read the question too quickly; if you want the maximum of each sublist individually, Lye Fish provided it in the comments.

Upvotes: 3

Related Questions