Sorting an array by returning 1 or 0 or -1 if it returns these values how the sort function can decide which one to put first

I don't understand the logic of sorting an array by returning 1 or 0 or -1 if it returns these values how the sort function can decide which one to put first

Example Let say we have an array

const newArray = [5.55, 4.3, 3.4, 1.8, 2.5];
const modifiedArray = newArray.sort((a, b) => {
  if (a > b) {
    return 1;
  } else if (a === b) {
    return 0;
  } else {
    return -1;
  }
});
console.log(modifiedArray);


Read more here: https://stackoverflow.com/questions/65717426/sorting-an-array-by-returning-1-or-0-or-1-if-it-returns-these-values-how-the-so

Content Attribution

This content was originally published by Code Centrix at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: