Auzy Auzy -4 years ago 100
Javascript Question

How to add JS .sort to Vue method

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()
})
},

Answer Source

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;
    }
  });
},
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download