N Min Elements

JavaScriptJavaScriptBeginner
Practice Now

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

Introduction

In this lab, we will explore the minN() function in JavaScript, which returns the n minimum elements from an array. We will learn how to use Array.prototype.sort() and Array.prototype.slice() methods to create a shallow clone of the array, sort it in ascending order, and get the specified number of elements. By the end of this lab, you will have a better understanding of how to manipulate arrays in JavaScript using these methods.


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-28505{{"`N Min Elements`"}} javascript/data_types -.-> lab-28505{{"`N Min Elements`"}} javascript/arith_ops -.-> lab-28505{{"`N Min Elements`"}} javascript/comp_ops -.-> lab-28505{{"`N Min Elements`"}} javascript/spread_rest -.-> lab-28505{{"`N Min Elements`"}} end

Function to Return N Minimum Elements of an Array

To practice coding, open the Terminal/SSH and type node. Use the minN function to return the n minimum elements from an array.

Here's how to use the function:

  • Use Array.prototype.sort() and the spread operator (...) to create a shallow clone of the array and sort it in ascending order.
  • Use Array.prototype.slice() to get the specified number of elements.
  • If you omit the second argument, n, the function will return a one-element array.
  • If n is greater than or equal to the length of the provided array, the function will return the original array, sorted in ascending order.
const minN = (arr, n = 1) => [...arr].sort((a, b) => a - b).slice(0, n);

Here are some examples:

minN([1, 2, 3]); // [1]
minN([1, 2, 3], 2); // [1, 2]

Summary

Congratulations! You have completed the N Min Elements lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like