Ordering arrays in Javascript

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 …


This content originally appeared on DEV Community 👩‍💻👨‍💻 and was authored by John Muthua

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 ]

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' ]

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' ]

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' ]

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' ]

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"

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);
}

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

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

Leave a like ❤️ if you found this useful
Happy coding 🔥 🔥


This content originally appeared on DEV Community 👩‍💻👨‍💻 and was authored by John Muthua


Print Share Comment Cite Upload Translate Updates
APA

John Muthua | Sciencx (2022-09-23T18:58:17+00:00) Ordering arrays in Javascript. Retrieved from https://www.scien.cx/2022/09/23/ordering-arrays-in-javascript/

MLA
" » Ordering arrays in Javascript." John Muthua | Sciencx - Friday September 23, 2022, https://www.scien.cx/2022/09/23/ordering-arrays-in-javascript/
HARVARD
John Muthua | Sciencx Friday September 23, 2022 » Ordering arrays in Javascript., viewed ,<https://www.scien.cx/2022/09/23/ordering-arrays-in-javascript/>
VANCOUVER
John Muthua | Sciencx - » Ordering arrays in Javascript. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2022/09/23/ordering-arrays-in-javascript/
CHICAGO
" » Ordering arrays in Javascript." John Muthua | Sciencx - Accessed . https://www.scien.cx/2022/09/23/ordering-arrays-in-javascript/
IEEE
" » Ordering arrays in Javascript." John Muthua | Sciencx [Online]. Available: https://www.scien.cx/2022/09/23/ordering-arrays-in-javascript/. [Accessed: ]
rf:citation
» Ordering arrays in Javascript | John Muthua | Sciencx | https://www.scien.cx/2022/09/23/ordering-arrays-in-javascript/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.