Introduction
In this lab, we will be exploring how to order an array of objects based on a given property and a custom order array. We will be using a combination of Array.prototype.reduce() and Array.prototype.sort() to create a new array that is sorted based on the order provided in the order array. This lab is a great opportunity to learn how to manipulate arrays of objects in JavaScript.
How to Order an Array of Objects Based on Property Order
To order an array of objects based on a property order, follow these steps:
- Open the Terminal/SSH and type
nodeto start practicing coding. - Use
Array.prototype.reduce()to create an object from theorderarray with the values as keys and their original index as the value. - Use
Array.prototype.sort()to sort the given array, skipping elements for whichpropis empty or not in theorderarray.
Here's an example code snippet for ordering an array of objects based on a property order:
const orderWith = (arr, prop, order) => {
const orderValues = order.reduce((acc, v, i) => {
acc[v] = i;
return acc;
}, {});
return [...arr].sort((a, b) => {
if (orderValues[a[prop]] === undefined) return 1;
if (orderValues[b[prop]] === undefined) return -1;
return orderValues[a[prop]] - orderValues[b[prop]];
});
};
You can use the orderWith function to order an array of objects based on a property order. For example:
const users = [
{ name: "fred", language: "Javascript" },
{ name: "barney", language: "TypeScript" },
{ name: "frannie", language: "Javascript" },
{ name: "anna", language: "Java" },
{ name: "jimmy" },
{ name: "nicky", language: "Python" }
];
orderWith(users, "language", ["Javascript", "TypeScript", "Java"]);
/*
[
{ name: 'fred', language: 'Javascript' },
{ name: 'frannie', language: 'Javascript' },
{ name: 'barney', language: 'TypeScript' },
{ name: 'anna', language: 'Java' },
{ name: 'jimmy' },
{ name: 'nicky', language: 'Python' }
]
*/
Summary
Congratulations! You have completed the Order Array of Objects Based on Property Order lab. You can practice more labs in LabEx to improve your skills.