
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Retrieve N Smallest Numbers from an Array in JavaScript
Problem
We are required to write a JavaScript function that takes in an array of numbers arr, and a number n.
Our function should retrieve the n smallest from the array arr without disturbing their relative order. It means they should not be arranged in increasing or decreasing order rather they should hold their original order.
Example
Following is the code −
const arr = [6, 3, 4, 1, 2]; const num = 3; const smallestInOrder = (arr = [], num) => { if(arr.length < num){ return arr; }; const copy = arr.slice(); copy.sort((a, b) => a - b); const required = copy.splice(0, num); required.sort((a, b) => { return arr.indexOf(a) - arr.indexOf(b); }); return required; }; console.log(smallestInOrder(arr, num));
Output
Following is the console output −
[3, 1, 2]
Advertisements