How to sort an Array in TypeScript

avatar

Borislav Hadzhiev

Mon Feb 21 20223 min read

banner

Photo by Chester Wade

Sort an Array in TypeScript #

Use the sort() method to sort an array in TypeScript, e.g. numArray.sort((a, b) => a - b). The sort method takes a function that defines the sort order as a parameter. The function has to be provided when sorting a numeric array, but is optional when sorting string arrays.

index.ts
// ✅ for Numbers const numArray: number[] = [15, 4, 1, 8]; const result1 = numArray.sort((a, b) => a - b); console.log(result1); // 👉️ [1, 4, 8, 15] // ✅ for Strings const strArray: string[] = ['z', 'c', 'a', 'f']; const result2 = strArray.sort(); console.log(result2); // 👉️ ['a', 'c', 'f', 'z'] // ✅ For Objects const objArray: { num: number }[] = [ { num: 15 }, { num: 4 }, { num: 1 }, { num: 8 }, ]; const result3 = objArray.sort((obj1, obj2) => { if (obj1.num > obj2.num) { return 1; } if (obj1.num < obj2.num) { return -1; } return 0; }); console.log(result3); // 👉️ [{num: 1}, {num: 4}, {num: 8}, {num: 15}]

We used the Array.sort method to sort a numeric and string array in TypeScript.

Note that the sort() method sorts the elements of the array in place and returns the sorted array. In other words, it mutates the original array.

index.ts
const numArray: number[] = [15, 4, 1, 8]; const result1 = numArray.sort((a, b) => a - b); console.log(result1); // 👉️ [1, 4, 8, 15] console.log(numArray); // 👉️ [1, 4, 8, 15]

If you want to sort the arrays without mutating them, use the spread syntax (...) to create a shallow copy before calling the sort() method.

index.ts
// ✅ for Numbers const numArray: number[] = [15, 4, 1, 8]; const result1 = [...numArray].sort((a, b) => a - b); console.log(result1); // 👉️ [1, 4, 8, 15] console.log(numArray); // 👉️ [15, 4, 1, 8] // ✅ for Strings const strArray: string[] = ['z', 'c', 'a', 'f']; const result2 = [...strArray].sort(); console.log(result2); // 👉️ ['a', 'c', 'f', 'z'] console.log(strArray); // 👉️ ['z', 'c', 'a', 'f']

We used the spread syntax (...) to unpack the values of the array into a new array before calling the sort method.

This is probably what you want to be doing since mutations can be confusing and difficult to track throughout a codebase.

When sorting a numbers array, we have to pass a function to the sort() method, whereas with strings - we don't.

The parameter we passed to the method in the first example is a function that defines the sort order.

If the function parameter is not provided to the sort method, the array elements get converted to strings and sorted according to their UTF-16 code unit values.

This is not what you want when working with number arrays, however it's exactly what you want when sorting string arrays.

The last example shows how to sort an array of objects.

index.ts
// ✅ For Objects const objArray: { num: number }[] = [ { num: 15 }, { num: 4 }, { num: 1 }, { num: 8 }, ]; const result3 = objArray.sort((obj1, obj2) => { if (obj1.num > obj2.num) { return 1; } if (obj1.num < obj2.num) { return -1; } return 0; }); console.log(result3); // 👉️ [{num: 1}, {num: 4}, {num: 8}, {num: 15}]

The sort() method uses the following logic to sort the elements in the array:

  • If the return value of the compare function is greater than 0, then sort b before a.

  • If the return value of the compare function is less than 0, then sort a before b.

  • If the return value of the compare function is equal to 0, keep the original order of a and b.

You can use the same approach to sort an array of objects by a string property.

index.ts
// ✅ For Objects const objArray: { str: string }[] = [ { str: 'z' }, { str: 'c' }, { str: 'a' }, { str: 'f' }, ]; const result3 = objArray.sort((obj1, obj2) => { if (obj1.str > obj2.str) { return 1; } if (obj1.str < obj2.str) { return -1; } return 0; }); console.log(result3); // 👉️ [{str: 'a'}, {str: 'c'}, {str: 'f'}, {str: 'z'}]
Use the search field on my Home Page to filter through my more than 1,000 articles.