Reputation: 2155
I have the following Vue method that I need to add JS .sort()
to in order to order output alphabetically. I learned JS backward learning framework first and am struggling to understand how I need to make this work JS-wise:
filteredByCat (cat) {
return this.businesses.filter((element) => {
return element.cat === cat.name
})
},
Somehow I need something like this:
filteredByCat (cat) {
return this.businesses.filter((element) => {
return (element.cat === cat.name).sort()
})
},
Upvotes: 0
Views: 90
Reputation: 55644
You need to sort the filtered array:
filteredByCat (cat) {
return this.businesses.filter((element) => {
return (element.cat === cat.name);
}).sort();
},
From the MDN Documentation for Array.prototype.sort():
The default sort order is according to string Unicode code points.
This means the above example will sort the filtered businesses
array as strings in alphabetical and ascending order.
If you need to sort an array of objects by a property (say name
), you need to provide a callback function as a parameter which provides the sort logic:
filteredByCat (cat) {
return this.businesses.filter((element) => {
return (element.cat === cat.name);
}).sort((a, b) => { // based off an example in the MDN Documentation for .sort()
var nameA = a.name.toUpperCase();
var nameB = b.name.toUpperCase();
if (nameA < nameB) {
return -1;
} else if (nameA > nameB) {
return 1;
} else {
return 0;
}
});
},
Upvotes: 1
Reputation: 1123
the sort function requires a callback like
.sort(function(a,b) { return a-b })
Upvotes: 0