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

We need to write a JavaScript function that takes an array of numbers and a number n, then returns the n smallest numbers while preserving their original order in the array.

Problem

Given an array of numbers and a value n, we want to find the n smallest numbers but maintain their relative positions from the original array. The result should not be sorted numerically but should appear in the same order as they existed in the input array.

Example

Here's how we can solve this problem:

const arr = [6, 3, 4, 1, 2];
const num = 3;

const smallestInOrder = (arr = [], num) => {
    if(arr.length < num){
        return arr;
    };
    
    // Create a sorted copy to find the smallest elements
    const copy = arr.slice();
    copy.sort((a, b) => a - b);
    const required = copy.splice(0, num);
    
    // Sort by original order using indexOf
    required.sort((a, b) => {
        return arr.indexOf(a) - arr.indexOf(b);
    });
    
    return required;
};

console.log(smallestInOrder(arr, num));
[3, 1, 2]

How It Works

The function follows these steps:

  1. Edge case handling: If the array length is less than n, return the entire array
  2. Find smallest elements: Create a sorted copy and take the first n elements
  3. Preserve original order: Sort these n elements based on their original positions using indexOf()

Alternative Approach Using Filter and Sort

Here's another method that might be more efficient for larger arrays:

const smallestInOrderV2 = (arr = [], num) => {
    if(arr.length <= num) return arr;
    
    // Find the nth smallest value as threshold
    const sorted = [...arr].sort((a, b) => a - b);
    const threshold = sorted[num - 1];
    
    let count = 0;
    return arr.filter(item => {
        if(item <= threshold && count < num) {
            count++;
            return true;
        }
        return false;
    });
};

const testArr = [8, 3, 7, 1, 2, 5];
console.log(smallestInOrderV2(testArr, 4));
[3, 1, 2, 5]

Comparison of Methods

Method Time Complexity Space Complexity Handles Duplicates
indexOf Approach O(n² log n) O(n) Partially
Filter Approach O(n log n) O(n) Better

Edge Cases

// Test with duplicates
console.log(smallestInOrder([5, 2, 2, 1, 3], 3));

// Test when n is larger than array length
console.log(smallestInOrder([1, 2], 5));

// Test with single element
console.log(smallestInOrder([7], 1));
[2, 2, 1]
[1, 2]
[7]

Conclusion

Both approaches successfully retrieve the n smallest numbers while maintaining their original order. The indexOf method is simpler but less efficient with duplicates, while the filter approach handles edge cases better and has better time complexity.

Updated on: 2026-03-15T23:19:00+05:30

433 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements