Introduction
In this lab, we will explore the maxN function which is used to return the n maximum elements from a given array. We will learn how to use Array.prototype.sort(), the spread operator (...), and Array.prototype.slice() to sort and slice the array in descending order and return the specified number of elements. This lab will help you improve your understanding of manipulating arrays in JavaScript.
How to Get N Max Elements from an Array in JavaScript
To practice coding in JavaScript, open the Terminal/SSH and type node. Once you've done that, you can use the following steps to get the n maximum elements from an array:
- Use
Array.prototype.sort()along with the spread operator (...) to create a shallow clone of the array and sort it in descending order. - Use
Array.prototype.slice()to get the specified number of elements. - If you omit the second argument,
n, you will get a one-element array by default. - If
nis greater than or equal to the provided array's length, then return the original array (sorted in descending order).
Here's the JavaScript code for the maxN function that implements these steps:
const maxN = (arr, n = 1) => [...arr].sort((a, b) => b - a).slice(0, n);
You can test the maxN function with the following examples:
maxN([1, 2, 3]); // [3]
maxN([1, 2, 3], 2); // [3, 2]
Summary
Congratulations! You have completed the N Max Elements lab. You can practice more labs in LabEx to improve your skills.