1

Googling around I found this function to sort an array by integer size easily, and tested it out in jsfiddle, works as intended (console logs 140000, 104, 99).

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

var numArray = [104, 99, 140000];
numArray.sort(sortNumber);
console.log(numArray);

So I tried to implement it in a solution for a freeCodeCamp exericse, and somehow can't get it to work. The only difference is that now I have a nested array to process. So I want to loop trough all the arrays nested in the arr element (for example largetsOfFour), and sort the integers inside the arrays by size. Can anyone point out what I'm doing wrong?

function largestOfFour(arr) {
  for(var x=0; x<arr.lenght; x++) {
    arr[x] = arr[x].sort(function(a,b) { return b - a; });
  }
  return arr;
}

largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
1
  • remplace arr.lenght by arr.length. And pls, check your logs next time. :) Commented Dec 1, 2015 at 14:27

1 Answer 1

3

There is a typo. It should have been arr.length, not arr.lenght.

Since there is no such property called lenght exists in arr, it returns undefined.

console.log([].lenght);
// undefined

and undefined can never be compared with numbers. So when compared with x's initial value, zero, it returns false.

console.log(0 < undefined);
// false

It is because, when a number and another object are compared, both of them will be converted to numbers and undefined when converted to a number will return NaN and NaN will be equal to NOTHING (not even to itself).

console.log(+undefined);
// NaN
console.log(NaN === NaN);
// false

So the loop in largestOfFour is never executed and so the sorting functions are. That is why your arrays are not sorted at all.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.