Building an E-Commerce Store - Browsing Products Chapter 10
if(this.ordering.length) {
let orders = this.ordering.split('-');
output = this.products.sort(function(a, b) {
if(typeof a[orders[0]] == 'string') {
return a[orders[0]].localeCompare(b[orders[0]]);
} else {
return a[orders[0]] - b[orders[0]];
}
});
} else {
output = this.products;
}
return output;
}
Lastly, we need to check if the second item in the orders array is asc or desc. By default,
the current sort function will return the items sorted in an ascending order, so if the value
is desc, we can reverse the array:
orderProducts() {
let output;
if(this.ordering.length) {
let orders = this.ordering.split('-');
output = this.products.sort(function(a, b) {
if(typeof a[orders[0]] == 'string') {
return a[orders[0]].localeCompare(b[orders[0]]);
} else {
return a[orders[0]] - b[orders[0]];
}
});
if(orders[1] == 'desc') {
output.reverse();
}
} else {
output = this.products;
}
return output;
}
Head to your browser and check out the ordering of products!