From 02206a21232aa2df76797c7cdb0c713e23ccc30f Mon Sep 17 00:00:00 2001 From: Utkarsh Raj Singh Date: Tue, 23 Oct 2018 04:01:24 +0530 Subject: [PATCH] Modified the sort function (#25978) Modification in the sort function to implement the better practice of returning 0 for the same elements. Not implementing the practice can break the function in new browsers. --- ...ort-an-array-alphabetically-using-the-sort-method.english.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/curriculum/challenges/english/02-javascript-algorithms-and-data-structures/functional-programming/sort-an-array-alphabetically-using-the-sort-method.english.md b/curriculum/challenges/english/02-javascript-algorithms-and-data-structures/functional-programming/sort-an-array-alphabetically-using-the-sort-method.english.md index d410660171..45bad56d7c 100644 --- a/curriculum/challenges/english/02-javascript-algorithms-and-data-structures/functional-programming/sort-an-array-alphabetically-using-the-sort-method.english.md +++ b/curriculum/challenges/english/02-javascript-algorithms-and-data-structures/functional-programming/sort-an-array-alphabetically-using-the-sort-method.english.md @@ -8,7 +8,7 @@ challengeType: 1
The sort method sorts the elements of an array according to the callback function. For example: -
function ascendingOrder(arr) {
  return arr.sort(function(a, b) {
    return a - b;
  });
}
ascendingOrder([1, 5, 2, 3, 4]);
// Returns [1, 2, 3, 4, 5]

function reverseAlpha(arr) {
  return arr.sort(function(a, b) {
    return a < b;
  });
}
reverseAlpha(['l', 'h', 'z', 'b', 's']);
// Returns ['z', 's', 'l', 'h', 'b']
+
function ascendingOrder(arr) {
  return arr.sort(function(a, b) {
    return a - b;
  });
}
ascendingOrder([1, 5, 2, 3, 4]);
// Returns [1, 2, 3, 4, 5]

function reverseAlpha(arr) {
  return arr.sort(function(a, b) {
    return a === b ? 0 : a < b ? : 1 : -1;
  });
}
reverseAlpha(['l', 'h', 'z', 'b', 's']);
// Returns ['z', 's', 'l', 'h', 'b']
Note: It's encouraged to provide a callback function to specify how to sort the array items. JavaScript's default sorting method is by string Unicode point value, which may return unexpected results.