Skip to content
Advertisement

Sorting with Number and Strings in array of objects

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.

Advertisement

Answer

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);
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement