
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Sorting Array with JavaScript Reduce Function
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 ]
Advertisements