Single Dimensional Array sort

 

sort()

The sort() method sorts the items of an array in descending or ascending order. Also, function sort the value as a string.

Alphabetic Sort

For Example :

let b = [“cat”, “man”, “dog”];

b.sort();
Output : [“cat”, “dog”, “man”] (ascending order)

b.reverse();
Output : [“man”, “dog”, “cat”] (descending order)

Number sort

Example:

let a = [4,2,7,3,1];

a.sort();
Output : [1, 2, 3, 4, 7](ascending order)

a.reverse();
Output :  [7, 4, 3, 2, 1] (descending order)

But if array is [1, 100, 12, 25, 10] then
Output : [1, 10, 100, 12, 25]

So for number sorting, array can be sort using “compare function”.

Example:

let a = [1, 10, 100, 12, 25];

a.sort((a,b) => (a – b))
output : [1, 10, 12, 25, 100] (ascending order)

a.sort((a,b) => (b – a))
output :  [100, 25, 12, 10, 1] (descending order)

Date sort

For date sorting, use new Date() function.

Example

let a = [“12-10-2020”, “10-15-2021”, “11-12-2020”] (MM-DD-YYYY format)

a.sort((a,b) => new Date(b) – new Date(a))

Output: [“10-15-2021”, “12-10-2020”, “11-12-2020”]

let b = [“2020-12-12”, “2021-10-15”, “2010-09-19”] (YYYY-MM-DD format)

Output : [“2021-10-15”, “2020-12-12”, “2010-09-19”]

Refer: https://jsfiddle.net/lochawala/cqwtyx7g/

Multidimensional Array Sorting

let multi_array =
[{
name : “rahul”,
age : 20
},{
name : “tina”,
age : 18,
},{
name : “geeta”,
age : 24
}];

For sorting string value in multidimensional-array

Example

(Ascending order)

multi_array.sort((a,b) =>
{
let a1 = a.name.toUpperCase(),
b1 = b.name.toUpperCase();
return a1 == b1 ? 0 : a1 > b1 ? 1 : -1;
});

Output : [{name: “geeta”, age: 24},
              {name: “rahul”, age: 20},
              {name: “tina”, age: 18}]

(Descending order)

multi_array.sort((a,b) =>{
let a1 = a.name.toUpperCase(),
b1 = b.name.toUpperCase();
return a1 == b1 ? 0 : a1 < b1 ? 1 : -1;
});

Output : [{name: “tina”, age: 18},
             {name: “rahul”, age: 20},
             {name: “geeta”, age: 24}]

Example for sorting number value in multidimensional array

multi_array.sort((a,b) =>
{ return a.age – b.age }
)

Output : [{name: “tina”, age: 18},
             {name: “rahul”, age: 20},
            {name: “geeta”, age: 24}]

Refer: https://jsfiddle.net/lochawala/7fypt53s/

LEAVE A REPLY

Please enter your comment!
Please enter your name here