JavaScript fundamental: Get a sorted array of objects ordered by properties and orders
JavaScript fundamental (ES6 Syntax): Exercise-37 with Solution
Write a JavaScript program to get a sorted array of objects ordered by properties and orders.
- Uses Array.prototype.sort(), Array.prototype.reduce() on the props array with a default value of 0.
- Use array destructuring to swap the properties position depending on the order supplied.
- If no orders array is supplied, sort by 'asc' by default.
Sample Solution:
JavaScript Code:
//#Source https://bit.ly/2neWfJ2
const orderBy = (arr, props, orders) =>
[...arr].sort((a, b) =>
props.reduce((acc, prop, i) => {
if (acc === 0) {
const [p1, p2] = orders && orders[i] === 'desc' ? [b[prop], a[prop]] : [a[prop], b[prop]];
acc = p1 > p2 ? 1 : p1 < p2 ? -1 : 0;
}
return acc;
}, 0)
);
const users = [{ name: 'fred', age: 48 }, { name: 'barney', age: 36 }, { name: 'fred', age: 40 }];
console.log(orderBy(users, ['name', 'age'], ['asc', 'desc']));
console.log(orderBy(users, ['name', 'age']));
Sample Output:
[{"name":"barney","age":36},{"name":"fred","age":48},{"name":"fred","age":40}] [{"name":"barney","age":36},{"name":"fred","age":40},{"name":"fred","age":48}]
Flowchart:

Live Demo:
See the Pen javascript-basic-exercise-1-37 by w3resource (@w3resource) on CodePen.
Improve this sample solution and post your code through Disqus
Previous: Write a JavaScript program to create a function that invokes each provided function with the arguments it receives and returns the results.
Next: Write a JavaScript program to pad a string on both sides with the specified character, if it's shorter than the specified length.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends
- Python Interview Questions and Answers: Comprehensive Guide
- Scala Exercises, Practice, Solution
- Kotlin Exercises practice with solution
- MongoDB Exercises, Practice, Solution
- SQL Exercises, Practice, Solution - JOINS
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join