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 with 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];

Example

Following is the code −

// we will sort this array but
// without using the array sort function
// without using any kind of conventional loops
// using the ES6 function reduce()
const arr = [4, 56, 5, 3, 34, 37, 89, 57, 98];
const sortWithReduce = arr => {
   return arr.reduce((acc, val) => {
      let ind = 0;
      while(ind < arr.length && val < arr[ind]){
         ind++;
      }
      acc.splice(ind, 0, val);
      return acc;
   }, []);
};
console.log(sortWithReduce(arr));

Output

This will produce the following output in console −

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

Updated on: 30-Sep-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements