Sorting An Array In JavaScript

In this tutorial we will learn , How to sort different types of array in JavaScript. Generally sorting needed in table’s column. On clicking the column name it sorted by ascending or descending order. We will sort a string array, integer array and objective array with examples.

how to sort an array in javascript
how to sort an array in JavaScript

How to sort an array in JavaScript?

  1. Sorting a string array.
  2. Numeric sorting an array.
  3. Sorting a objective array.

1. Sorting a String Array?

To sort a string array, we can use its inbuilt function sort(). The array will be sorted alphabetically(A-Z). See the example below.

var fruits = ["banana", "apple",  "mango", "kiwi"]

var sortedFruits = fruits.sort()

result : apple, banana, kiwi, mango

Reversing an array

We can reverse an array using the reverse() (from Z-A) function as below.

var fruits = ["banana", "apple",  "mango", "kiwi"]

var reversedFruits = fruits.reverse()

result : mango, kiwi, banana, apple

2. Sorting a Numeric Array.

By default the sort() function sorts strings. But we can sort numeric values by comparing each other. Using a-b sorted by ascending order of numeric values.

var numbers = [23, 45,12, 100, 10];
var sorted = numbers.sort(function(a, b) return { a - b } );
result : 10, 12, 23, 45, 100

To sort by descending order we have to use b-a inside the function like below:

b-a : Getting the value which is less than to the next value.

var numbers = [23, 45,12, 100, 10];
var sorted = numbers.sort(function(a, b) return { b - a } );
result : 100, 45, 23, 12, 10

3. Sorting an Objective Array in JavaScript.

Arrays can be objective type like as below: Use the key name to sort this type of array.

const cars = [
  {type:"YAMAHA", year:2010}
  {type:"BMW", year:2016},
  {type:"HONDA", year:2001},
];

var sortedCars = cars.sort((a,b) return {a. year - b.year})
result : 
BMW 2016
HONDA 2001
YAMAHA 2010

Thank you for visiting the page on FlutterTpoint. If you have any questions or doubts you can comment in the comments section below.

Don’t miss new tips!

We don’t spam! Read our [link]privacy policy[/link] for more info.

Leave a Comment