- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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 - 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 ]
- Related Articles
- JavaScript reduce sum array with undefined values
- Reduce array in JavaScript
- Sorting or Arranging an Array with standard array values - JavaScript
- JavaScript array sorting by level
- Sorting Array based on another array JavaScript
- Uneven sorting of array in JavaScript
- Finding the product of array elements with reduce() in JavaScript
- Reduce an array to groups in JavaScript
- Sorting an array of binary values - JavaScript
- Sorting Array without using sort() in JavaScript
- Sorting an array by date in JavaScript
- Sorting parts of array separately in JavaScript
- Sorting an array by price in JavaScript
- Alternative sorting of an array in JavaScript
- How to write the factorial function with reduce and range in JavaScript?

Advertisements