Retrieving n smallest numbers from an array in their original order in JavaScript

JavascriptWeb DevelopmentFront End Technology

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 −

 Live Demo

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]
raja
Published on 19-Apr-2021 08:14:11
Advertisements