Computer >> Computer tutorials >  >> Programming >> Javascript

Sorting Array without using sort() in JavaScript


We are required to write a JavaScript function that takes in an array of numbers.

The function should sort the array using the Array.prototype.sort() method, but, here, we are required to use the Array.prototype.reduce() method to sort the array.

Therefore, let’s write the code for this function −

Example

The code for this will be −

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

The output in the console will be −

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