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