Sort method to sort arrays

Sort method to sort arrays

The sort method sorts the elements of an array according to the callback function.

For example on an array of numbers:

function ascendingOrder(arr) {
  return arr.sort(function(a, b) {
    return a - b;
  });
}

ascendingOrder([1, 5, 2, 3, 4]); // => [1, 2, 3, 4, 5]

To reverse it and sort the array in descending order, simple pass b - a.

function alphabeticalOrder(arr) {
  // Add your code below this line
  return arr.sort(function(a, b) {
    return a === b ? 0 : a < b ? -1 : 1;
  });
  // Add your code above this line
}
alphabeticalOrder(["a", "d", "c", "a", "z", "g"]); // => ["a", "a", "c", "d", "g", "z"]

To reverse the order:

function reverseAlpha(arr) {
  return arr.sort(function(a, b) {
    return a === b ? 0 : a < b ? 1 : -1;
  });
}

reverseAlpha(['l', 'h', 'z', 'b', 's']); // => ["z", "s", "l", "h", "b"]

This would return the value ['z', 's', 'l', 'h', 'b'].

JavaScript's default sorting method is by string Unicode point value, which may return unexpected results. Therefore, it is encouraged to provide a callback function to specify how to sort the array items.

Return a Sorted Array Without Changing the Original Array

A side effect of the sort method is that it changes the order of the elements in the original array. In other words, it mutates the array in place. One way to avoid this is to first concatenate an empty array to the one being sorted (remember that slice and concat return a new array), then run the sort method.

Example:

const globalArray = [5, 6, 3, 2, 9, 5, 2, 10];

function nonMutatingSort(arr) {
  // Only change code below this line

  return [].concat(arr).sort(function(a, b) { // add an empty array that we then combine with arr
    return a === b ? 0 : a < b ? -1 : 1;
  });
  // Only change code above this line
}

nonMutatingSort(globalArray);

Console logging both arrays, we get the following:

console.log(nonMutatingSort(globalArray)); ==> [ 2, 2, 3, 5, 5, 6, 9, 10 ]
console.log(globalArray) // => [5, 6, 3, 2, 9, 5, 2, 10]