Categories
JavaScript Answers

How to rank array elements with JavaScript?

Spread the love

Sometimes, we want to rank array elements with JavaScript.

In this article, we’ll look at how to rank array elements with JavaScript.

How to rank array elements with JavaScript?

To rank array elements with JavaScript, we can use the sort method.

For instance, we write:

const arr = [79, 5, 18, 5, 32, 1, 16, 1, 82, 13];
const sorted = arr.slice().sort((a, b) => b - a)
const ranks = arr.map(v => sorted.indexOf(v) + 1);
console.log(ranks);

We call arr.slice to make a copy of arr.

Then we call sort on it to return a sorted version of arr sorted in descending order.

Then we call arr.map with a callback that returns the position of the sorted array the arr entry v is in plus 1.

Therefore, ranks is [2, 7, 4, 7, 3, 9, 5, 9, 1, 6].

Since 79 is 2nd largest, 5 is 7th largest etc.

Conclusion

To rank array elements with JavaScript, we can use the sort method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *