Home > other >  Sorting with Number and Strings in array of objects
Sorting with Number and Strings in array of objects

Time:02-17

I have array like this :

array =[{limit:50}, {limit:40}, {limit:10},{limit:'unlimited'}]

How to sort this array so that, when ascending unlimited comes at the last index and when descending unlimited comes at the top index.

CodePudding user response:

The simplest may be to use the "standard" numerical sort for ascending, and when you need descending, then just apply .reverse() to it as an extra action:

let array =[{limit:50}, {limit:40}, {limit:10},{limit:'unlimited'}];

array.sort((a,b) => a.limit - b.limit);

console.log(array);

array.reverse();

console.log(array);

CodePudding user response:

Simplest and the most straightforward way is to use the Array built in functions of sort and reverse

In case you require ascending:

let array =[{limit:50}, {limit:40}, {limit:10},{limit:'unlimited'}]
array.sort((a,b) => a.limit - b.limit);

In case you require descending:

let array =[{limit:50}, {limit:40}, {limit:10},{limit:'unlimited'}]
array.sort((a,b) => a.limit - b.limit);
array.reverse();
  • Related