0

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()
  })
},
2
  • 1
    You should learn the basics of Javascript values, functions, and arrays. Commented Jun 12, 2017 at 19:16
  • @SLaks I agree, working on that. Frameworks/libraries made more sense and I needed to know them for my job so I learned a little backward. Commented Jun 12, 2017 at 19:19

2 Answers 2

1

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;
    }
  });
},
Sign up to request clarification or add additional context in comments.

Comments

0

the sort function requires a callback like

.sort(function(a,b) { return a-b })

1 Comment

No, the callback parameter is optional. By default, the sort() method sorts the values as strings in alphabetical and ascending order. Try ["B", "A", "D", "C"].sort() in your console.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.