do you know if there is a way to sort an array of objects using the sort() method for a specific property? In my case I'd like to sort my array first for "bananas", then for "pears", and then the rest.
const initialData = [
{ name: "strawberries", value: 12 },
{ name: "bananas", value: 3 },
{ name: "pears", value: 8 },
{ name: "pears", value: 7 },
{ name: "bananas", value: 10 },
{ name: "apples", value: 6 },
{ name: "bananas", value: 13 },
{ name: "bananas", value: 5 }
]
This is how I'd like the sorted data to look like:
const sortedData = [
{ name: "bananas", value: 3 },
{ name: "bananas", value: 10 },
{ name: "bananas", value: 13 },
{ name: "bananas", value: 5 },
{ name: "pears", value: 8 },
{ name: "pears", value: 7 },
{ name: "strawberries", value: 12 },
{ name: "apples", value: 6 }
]
I know that this function would sort my data ascending or descending:
initialData.sort(function(a, b) {
if (a.name < b.name) {
return -1;
}
if (a.name > b.name) {
return 1;
}
return 0;
});
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…