Having hard time with sorting

Not sure why sort() mixing things up

function getIndexToIns(arr, num) {
  let copyArr = [...arr]; //not to mess with original data
  console.log('after copying  ', copyArr);
  copyArr.push(num);
  console.log('after pushing  ', copyArr);
  copyArr.sort();
  console.log('after sorting  ', copyArr);
  return copyArr.indexOf(num);
}


b = getIndexToIns([2, 5, 10], 15)


/*
after copying   [ 2, 5, 10 ]
after pushing   [ 2, 5, 10, 15 ]
after sorting   [ 10, 15, 2, 5 ]///////????????
*/

The sort method needs a callback function to correctly sort the numbers. You can read more the sort method here.

1 Like

I was confused because in Python similar method has some default behaviour like below. Thanks!

someList = [2, 5, 10 ,15]

someList.sort()

print(someList) #will print [2, 5, 10 ,15]

To be clear, so does JavaScript.

the array elements are converted to strings, then sorted according to each character’s Unicode code point value

1 Like

I guess if I wanna to sort numbers like numbers, this snippet from MDN is relevant enough?

var numbers = [4, 2, 5, 1, 3];
numbers.sort(function(a, b) {
  return a - b;
});
console.log(numbers); // [1, 2, 3, 4, 5]

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.