1 | initial version |
To categorize and sort objects using map and filter, you can follow these steps:
map()
to create a new array of the criteria you want to categorize the objects by. For example, if you want to categorize the objects by their type, you can use map()
to create a new array of the objects' types. filter()
to create an array of objects that belong in each category. For example, if the types are "fruit", "vegetable", and "meat", you can use filter()
to create an array of objects that have a type of "fruit", another array for "vegetable", and another array for "meat". sort()
.Here is an example code:
const products = [
{ name: 'banana', type: 'fruit', price: 1 },
{ name: 'broccoli', type: 'vegetable', price: 2},
{ name: 'chicken', type: 'meat', price: 5},
{ name: 'apple', type: 'fruit', price: 1.5},
{ name: 'carrot', type: 'vegetable', price: 1},
{ name: 'beef', type: 'meat', price: 8},
];
const types = products.map(product => product.type);
const fruits = products.filter(product => product.type === 'fruit').sort((a, b) => a.price - b.price);
const vegetables = products.filter(product => product.type === 'vegetable').sort((a, b) => a.name.localeCompare(b.name));
const meats = products.filter(product => product.type === 'meat').sort((a, b) => b.price - a.price);
In this example, we used map()
to create an array of types, and then used filter()
to create three new arrays for each type of product. We then sorted each array by a different property using sort()
.