-1

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.

Anil_M
  • 10,893
  • 6
  • 47
  • 74
Meet
  • 9
  • 4
  • Welcome to SO! Please take the [tour] and read "[ask]", "[Stack Overflow question checklist](https://meta.stackoverflow.com/questions/260648)" and their linked pages. We need to see your attempt to solve the problem. Without that, it looks like you didn't try and are asking us for references to off-site tutorials or to write code for you, which are both off-topic. – the Tin Man Mar 04 '22 at 21:12

2 Answers2

2

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);
trincot
  • 317,000
  • 35
  • 244
  • 286
  • 1
    if you want the reverse order, you can do it directly from the sort function. `array.sort((a,b) => b.limit - a.limit);` Reversing the array is an additional O(N) pass that can be avoided – Constantin Mar 01 '22 at 20:03
0

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();
Ammar
  • 106
  • 5