DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 967,611 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
John Muthua
John Muthua

Posted on

Ordering arrays in Javascript

ordering
The ordering of arrays is a common task while working with data. JavaScript provides numerous methods of accomplishing this task.

Method 1: Using sort function

NOTE: when using sort function to sort numbers in javascript it may be tempting to use it directly as:

const arr = [2, 13, 4, -75, 22, 5];
arr.sort(); //[ -75, 13, 2, 22, 4, 5 ]
Enter fullscreen mode Exit fullscreen mode

You realize that the results are not what you expected. Direct use of the sort function only works with strings as:

const arr2 = ["father", "mother", "children", "adam", "eve"];
arr2.sort();
//[ 'adam', 'children', 'eve', 'father', 'mother' ]
Enter fullscreen mode Exit fullscreen mode

Although the method provides the expected output, one should not that capital and small letters are treated differently. For example:

const arr3 = ["Eve", "adam"];
arr3.sort(); //[ 'Eve', 'adam' ]
Enter fullscreen mode Exit fullscreen mode

Notice in the array one would expect the a in adam to come before the E in Eve but that not the case with the sort function as uppercase letters always take presidence.
To solve this issue we may decide to convert the letters to lowercase then perform the sort as:

const arr3 = ["Eve", "adam"];
arr3.sort((a, b) => a.toLowerCase().localeCompare(b.toLowercase));
//[ 'adam', 'Eve' ]
Enter fullscreen mode Exit fullscreen mode

Now we get the expected results. Although this is a solution, there are concerns raised againist using toLowerCase expecially as they do not work with certain local languages.

Intl.Collator provides one with the ability to specify the sort order incomparision to the locales.

const arr3 = ["Eve", "adam"];
arr3.sort(Intl.Collator().compare);
//[ 'adam', 'Eve' ]
Enter fullscreen mode Exit fullscreen mode

As in the documentation example when dealing with Germany locale

const a = ["Offenbach", "Γ–sterreich", "Odenwald"];
const collator = new Intl.Collator("de-u-co-phonebk");
a.sort(collator.compare);
console.log(a.join(", "));
// β†’ "Odenwald, Γ–sterreich, Offenbach"
Enter fullscreen mode Exit fullscreen mode

Furthermore, Intl.Collator provides additional customizations as Intl.Collator('de', { sensitivity: 'base' }). Learn more here

Sorting Numbers

Method 1: Using the sort function

Using sort simplifies the work of arranging numbers in certain orders.
sort is used as below to arrange numbers

//smallest to Largest
function smallToLarge(arr) {
  return arr.sort((a, b) => a - b);
}

//largest to smallest
function largeToSmall(arr) {
  return arr.sort((a, b) => b - a);
}
Enter fullscreen mode Exit fullscreen mode

Note that rearranging from largest to smallest and vice versa may be simplified by using the reverse() method after performing a sort()

Method 2: Using a for loop

One may also use a for loop to arrange numbers within arrays in javascript

//Ordering from largest to smallest
function minMax(arr) {
  let tempArr = arr;
  let minMaxArr = [];
  for (let i = 0; i < arr.length; i++) {
    let min = Math.min(...tempArr);
    tempArr = tempArr.filter((item) => item !== min);
    minMaxArr.push(min);
  }
  return minMaxArr.pop();
}
Enter fullscreen mode Exit fullscreen mode

Here, we use the pop function to remove the last element of the array which in our case would be Infinity.
Finding the maximum would be simply replacing the min function with a max function as follows:

function maxMin(arr) {
  let tempArr = arr;
  let maxMinArr = [];
  for (let i = 0; i < arr.length; i++) {
    let max = Math.max(...tempArr);
    tempArr = tempArr.filter((item) => item !== max);
    maxMinArr.push(max);
  }
  return maxMinArr.pop();
}
Enter fullscreen mode Exit fullscreen mode

Leave a like ❀️ if you found this useful
Happy coding πŸ”₯ πŸ”₯

Top comments (0)

"I made 10x faster JSON.stringify() functions, even type safe"

☝️ Must read for JS devs