-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.

1
  • Welcome to SO! Please take the tour and read "How to Ask", "Stack Overflow question checklist" 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. Commented Mar 4, 2022 at 21:12

2 Answers 2

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);

Sign up to request clarification or add additional context in comments.

1 Comment

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
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();

1 Comment

How it is different from the above answer ?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.