Retrieve Maximum Elements from Array

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

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.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript(("`JavaScript`")) -.-> javascript/AdvancedConceptsGroup(["`Advanced Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") javascript/AdvancedConceptsGroup -.-> javascript/spread_rest("`Spread and Rest Operators`") subgraph Lab Skills javascript/variables -.-> lab-28504{{"`Retrieve Maximum Elements from Array`"}} javascript/data_types -.-> lab-28504{{"`Retrieve Maximum Elements from Array`"}} javascript/arith_ops -.-> lab-28504{{"`Retrieve Maximum Elements from Array`"}} javascript/comp_ops -.-> lab-28504{{"`Retrieve Maximum Elements from Array`"}} javascript/spread_rest -.-> lab-28504{{"`Retrieve Maximum Elements from Array`"}} end

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:

  1. Use Array.prototype.sort() along with the spread operator (...) to create a shallow clone of the array and sort it in descending order.
  2. Use Array.prototype.slice() to get the specified number of elements.
  3. If you omit the second argument, n, you will get a one-element array by default.
  4. If n is 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.

Other JavaScript Tutorials you may like