Sorting Array with JavaScript reduce function - JavaScript

We are required to write a JavaScript function that takes in an array of numbers. The function should sort the array without using the Array.prototype.sort() method. We are required to use the Array.prototype.reduce() method to sort the array.

Let's say the following is our array:

const arr = [4, 56, 5, 3, 34, 37, 89, 57, 98];

Understanding the Approach

The reduce() method can be used to build a sorted array by iterating through each element and placing it in the correct position within an accumulator array. We'll use insertion sort logic within the reduce function.

Example

Following is the code:

const arr = [4, 56, 5, 3, 34, 37, 89, 57, 98];

const sortWithReduce = arr => {
    return arr.reduce((acc, val) => {
        let ind = 0;
        // Find the correct position to insert the current value
        while(ind < acc.length && val > acc[ind]){
            ind++;
        }
        // Insert the value at the correct position
        acc.splice(ind, 0, val);
        return acc;
    }, []);
};

console.log(sortWithReduce(arr));

Output

This will produce the following output in console:

[
  3,  4,  5, 34, 37,
  56, 57, 89, 98
]

How It Works

The reduce() method starts with an empty array as the accumulator. For each element in the original array:

  • We find the correct position by comparing with existing elements in the accumulator
  • We use splice() to insert the element at the right position
  • The accumulator grows with each iteration, maintaining sorted order

Alternative Implementation

Here's another approach using reduce() for descending order:

const arr = [4, 56, 5, 3, 34, 37, 89, 57, 98];

const sortDescending = arr => {
    return arr.reduce((acc, val) => {
        let ind = 0;
        // For descending order, find where val is smaller
        while(ind < acc.length && val < acc[ind]){
            ind++;
        }
        acc.splice(ind, 0, val);
        return acc;
    }, []);
};

console.log(sortDescending(arr));
[
  98, 89, 57, 56, 37,
  34,  5,  4,  3
]

Conclusion

Using reduce() for sorting implements insertion sort logic, building a sorted array incrementally. While not as efficient as native sort(), it demonstrates reduce()'s versatility beyond simple aggregation tasks.

Updated on: 2026-03-15T23:18:59+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements