6

I have the following problem, my function accepts an array that contains 4 arrays, each element is a number. The functions must return the largest element of each array.

function largestOfFour(arr) {
  var largest = [];
  for (var i = 0; i < arr.length; i++) {
    largest.push(arr[i].sort().pop());
  }
  console.log(largest);
  return largest;
}

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

Results:

Array [ 5, 27, 39, 857 ]

Apparently it works, but when I tried with the last array [1000, 1001, 857, 1], in which 1000 and 1001 are larger than 857 I'm getting 857. Why does it happen?

L. San
  • 155
  • 6

3 Answers3

10

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

Array values are sorted as strings. If you want to sort as numbers, use a custom comparitor function.

From the MDN docs:

var numberArray = [40, 1, 5, 200];

function compareNumbers(a, b) {
  return a - b;
}

console.log('numberArray:', numberArray.join());
console.log('Sorted without a compare function:', numberArray.sort());
console.log('Sorted with compareNumbers:', numberArray.sort(compareNumbers));

output:

numberArray: 40,1,5,200
Sorted without a compare function: 1,200,40,5
Sorted with compareNumbers: 1,5,40,200

user229044
  • 232,980
  • 40
  • 330
  • 338
2

You are using the array#sort method which compares values as strings rather than as numbers. A better solution is using array.prototype.map and Math.max.apply

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

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

=> [5,27,39,1001]

You can also pass in a function to array#sort and do something like this

array.sort(function(a,b) { return a - b })

The pop() function removes and returns the last element of an array. In this case, that will be 1001.

RobG
  • 142,382
  • 31
  • 172
  • 209
Richard Hamilton
  • 25,478
  • 10
  • 60
  • 87
  • 1
    While a valid recommendation, this answer doesn't explain the effect for which the question seeks the cause. – das-g Sep 24 '15 at 22:35
2

Bottom line: 8 is bigger than 1.

Here's a concise article on the subject: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

Try this:

arr.sort(function(a, b){return a-b}).pop();

Or just Math.max()

PANDA Stack
  • 1,293
  • 2
  • 11
  • 30
  • Please don't reference [*w3schools*](http://www.w3fools.com/). [*ECMAScript 2015*](http://www.ecma-international.org/ecma-262/6.0/index.html#sec-array.prototype.sort) is the definitive reference, [*MDN*](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) is helpful for examples. – RobG Sep 24 '15 at 22:44
  • Okay - thanks! I'm on mobile now. I'll fix it in a bit. – PANDA Stack Sep 24 '15 at 23:07
  • @RobG The W3Fools page no longer seems that critical of W3Schools: "W3Schools still has issues but they have at least worked on the primary concern developers had. For many beginners, W3Schools has structured tutorials and playgrounds that offer a decent learning experience." – Kyle Strand Sep 24 '15 at 23:07
  • @KyleStrand—I expect the authors of that page were approached by w3schools to tone down their criticism or face legal consequences. w3schools remains a commercial site that touts for business, they do not need free plugs and there are still significant technical errors in the site content. MDN is not free of errors, but at least anyone with an interest can fix them and improve the content. – RobG Sep 25 '15 at 01:09