This question has already been answered:

It turns out what's the problem, for some reason, the .sort () method for me does not sort the last 6-digit array. What could be problematic?

function median(data) { // var count = 0; x = data; x.sort(); // // for (var i = 0; i < data.length; i++) { // if (data.length === 5 || data.length === 3) { // data.pop(); // data.shift(); // } else if (data.length === 6 || data.length === 4) { // data.pop(); // data.shift(); // } // if (data.length === 2) { // for (var j = 0; j < data.length; j++) { // count = (data[0] + data[1]); // return count / 2; // } // } // } return data; } console.log(median([1, 2, 3, 4, 5])); console.log(median([3, 1, 2, 5, 3])); console.log(median([1, 300, 2, 200, 1])); console.log(median([3, 6, 20, 99, 10, 15])); 

Reported as a duplicate at Grundy. javascript 11 May '18 at 15:21 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

    1 answer 1

    Sorting by default compares the elements of the array as strings. Js looks at a pair, for example, 100, 99 as on "100", "99" - in this case "100" less than "99" .

     function median(data) { data.sort((a, b) => a - b); return data; } console.log(median([1, 2, 3, 4, 5])); console.log(median([3, 1, 2, 5, 3])); console.log(median([1, 300, 2, 200, 1])); console.log(median([3, 6, 20, 99, 10, 15])); 

    • Well, you already answered the same question twice - Grundy
    • Damn it, I already answered it). - Igor
    • twice !!! Every year count :-) - Grundy
    • @Grundy Year - for two. - Igor
    • one
      @BraFik Js looks at a pair, for example, 100, 99 as on "100", "99" - in this case "100" less than "99" . - Igor