Ordering arrays in Javascript
Tags: javascript, tutorial, interview
Published: 2022-09-23 18:58:17

![ordering](https://www.freecodecamp.org/news/content/images/size/w2000/2021/09/brett-jordan-M3cxjDNiLlQ-unsplash.jpg)
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:

```js
const arr = [2, 13, 4, -75, 22, 5];
arr.sort(); //[ -75, 13, 2, 22, 4, 5 ]
```

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

```js
const arr2 = ["father", "mother", "children", "adam", "eve"];
arr2.sort();
//[ 'adam', 'children', 'eve', 'father', 'mother' ]
```

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

```js
const arr3 = ["Eve", "adam"];
arr3.sort(); //[ 'Eve', 'adam' ]
```

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:

```js
const arr3 = ["Eve", "adam"];
arr3.sort((a, b) => a.toLowerCase().localeCompare(b.toLowercase));
//[ 'adam', 'Eve' ]
```

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.

```js
const arr3 = ["Eve", "adam"];
arr3.sort(Intl.Collator().compare);
//[ 'adam', 'Eve' ]
```
As in the documentation example when dealing with Germany locale

```js
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"
```

Furthermore, `Intl.Collator` provides additional customizations as `Intl.Collator('de', { sensitivity: 'base' })`. Learn more [here] (<https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator/compare>)

## 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

```js
//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);
}
```
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


```js
//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();
}
```
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:

```js
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();
}
```

Leave a like :heart: if you found this useful
Happy coding :fire: :fire: