Data Structures & AlgorithmsVery hardGoogle · Flipkart interview

Edge case: Array sorting and parseInt in JavaScript.

Edge case: Array sorting and parseInt in JavaScript.
console.log([3, 20, 100].sort().join(","), [1, 2, 3].map(parseInt).join(","));
What is printed?
  1. A. 3,20,100 1,2,3
  2. B. 100,20,3 1,NaN,NaN
  3. C. 100,20,3 1,2,3
  4. D. 3,20,100 1,NaN,NaN

Correct answer: B. 100,20,3 1,NaN,NaN

Without a comparator, sort() compares values as strings, so '100' < '20' < '3'. map passes (value, index), so parseInt('1', 0) = 1, parseInt('2', 1) = NaN (radix 1 is invalid) and parseInt('3', 2) = NaN (3 is not a binary digit).

More Coding Interview Problems questions

Exams that ask this topic