What is the process for sorting a filtered array of strings alphabetically?

Currently, I am navigating through an array in my VUE application that holds the following structured data:

[
{
  "id": 1,
  "brands": [
    {
      "name": "Mall",
      "id": 1
    },
    {
      "name": "Tanted",
      "id": 25
    },
    {
      "name": "Anteil",
      "id": 12
    },
    {
      "name": "Moscard",
      "id": 73
    }
  ]
},
{
  "id": 2,
  "brands": [
    {
      "name": "Yanre",
      "id": 6
    },
    {
      "name": "Alted",
      "id": 10
    },
    {
      "name": "Sillex",
      "id": 9
    },
    {
      "name": "Straf",
      "id": 78
    }
  ]
}
]

To display the various select options based on id, I initially apply a filter by id as shown below:

computed: {
    filteredBrand() {
      var selectedBrand =
        !this.businessInfo || this.businessInfo.selectedBrand == 0
          ? 1
          : this.businessInfo.selectedBrand;
      return !this.$store.getters.brands
        ? null
        : this.$store.getters.brands.filter(
            item => item.id == selectedBrand
          )[0].brands;
    }
}


              <select
              v-model="businessInfo.selectedBrand"
              @change="onChangeBrand($event)">
              <option v-for="brand in filteredBrand" v-bind:key="brand.name">{{ brand.name }}</option>
              </select>


While successful in displaying brands corresponding to each id in alphabetical order is also desired. Despite attempts, combining the filter with sort proved challenging due to syntax errors. Here's the attempt made:

computed: {
    filteredBrand() {
      var selectedBrand =
        !this.businessInfo || this.businessInfo.selectedBrand == 0
          ? 1
          : this.businessInfo.selectedBrand;
      return !this.$store.getters.brands
        ? null
        : this.$store.getters.brands.filter(
            item => item.id == selectedBrand
          )[0].brands.sort(function(a, b) {
      return a.name === b.name ? 0 : +(a.name > b.name) || -1;
    });
    }
}


If anyone has insights on how to resolve this issue, your support and time are greatly appreciated.

Answer №1

If you want to compare two strings in alphabetical order from A-Z, use the following code within the sort callback:

return firstString.localeCompare(secondString);

For descending order (Z-A), simply switch the order like so:

return secondString.localeCompare(firstString);

On a side note: Instead of writing array.filter(/*...*/)[0], opt for array.find(/*...*/) instead. (You can polyfill find for IE support if needed.) The find method stops at the first matching entry and returns that specific entry without creating a new array with all matches. Why go through the whole array when you just need the first entry?

Putting this together with the main solution provided above:

  return !this.$store.getters.brands
    ? null
    : this.$store.getters.brands.find(
        item => item.id == selectedBrand
      ).brands.sort((firstBrand, secondBrand) => firstBrand.name.localeCompare(secondBrand.name));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The NPM command fails to execute the Webpack script, yet it successfully runs when manually entered into the terminal

Working on my project with Electron-React-Boilerplate, I encountered an issue while running npm run build-renderer. Despite the script appearing to finish, I receive an error. If I manually enter the code related to the build-renderer script in the termin ...

Design a function that accepts a string parameter and outputs an encoded (h4ck3r 5p34k) rendition of the input string

function convertToHacker(str){ for (var i=0; i <str.length;i++) { if (str[i]==="a") {str=str.replace("a","4")} else if (str[i]==="e") {str=str.replace("e","3")} else if (str[i]==="i") {str=str.replace("i","1") ...

The message sent from the server via SocketIO seems to be malfunctioning

Currently, I am in the process of developing an application that utilizes websockets for facilitating server-client communication. The main idea behind this concept is to enable the client to request messages from the server, while also allowing the server ...

Issue with React: Reading the 'pathname' property from undefined is not possible

I can't figure out why this error keeps popping up. My goal is to create animated transitions between Routes. Can anyone point out where I went wrong? view image description here I tried reinstalling the react-spring package but it didn't solve t ...

Accessing data outside of the scope when looping through items in Angular forEach

I am currently working on retrieving the Game ID generated by the APIService.postData method for the game. The goal is to utilize this Game ID within the Angular foreach loops to maintain foreign key constraints on the RESTful side. Any advice on extracti ...

Implementing interactive input binding with Vue.js for invoices

I was attempting to create invoice number four, but I got stuck in the process. Let me provide an example: If Quantity is 1 and Unit Price is 2000 with a Percent of 18, the net total should be "2360". Moreover, if the user updates the "net_total" value, I ...

Node.js is known for its unreliable promise returns

Currently, I have a function in place that establishes a connection with a sql database. After querying the database and formatting the results into an HTML table, the function returns the variable html: function getData() { return new Promise((resolv ...

Encountering an unhandled runtime error while importing the Client component into the server component: The JSON format is invalid, with the error message stating "undefined"

I've been attempting to create a basic counter component that increments the count of a state variable when a button is clicked. To achieve this, I created a separate file named Counter.tsx and placed it in the components folder at the root of my next ...

Storing information in Firebase using React.js

When storing an object in Firebase, I expected the structure to be as shown in the image below. However, what I received was a generated running number as a key. This is the code I used to store the object in Firebase: var location = []; location.push({ ...

Add a Page to Your Domain Name using the Text Input Box

I'm looking to create an input field that allows users to enter a text string, which will be added to a domain name when submitted, redirecting the user to a specific page. Here's how the process works: The user enters 'foo' into the ...

Stage setting timeout for the playwright

const test = defaultTest.extend({ audit: async ({ page }) => { await page.screenshot({ path: 'e2e/test.png' }); console.info('audit done!'); }, }); // ...more code test.only('audit', async ({ page, mount, audi ...

Tips for handling ng-if during element presence checks

There's a hidden div on my web page that is controlled by an ng-if directive. I'm looking to create a test that confirms the presence of the element only when it should be visible. If the condition set by ng-if is not met, the element is complete ...

In Reactjs, Axios and fetch are both commonly used for sending ongoing network requests to localhost

In order to establish a successful connection between the express backend and MongoDB database, I initially used fetch("/") from the frontend, which returned the index.html code. However, when I switched to fetch("http://localhost:9000"), I encountered a C ...

The ChromeDriver capabilities that have been configured are not maintained once the WebDriver is constructed in Node Selenium

I am currently experimenting with adding the default download path using Chrome capabilities in my code snippet below: const test = async () => { let builder = await new Builder().forBrowser("chrome"); let chromeCapabilities = builder.getC ...

When using ngClick with a parameter, the parameter is not being successfully passed

My table resembles a tree structure with two ng-repeats. <table> <tr ng-repeat-start="am in anArray"> <td><button ng-click="TheFunction(am)"></button></td> </tr> <tr ng-repeat-start="em in anotherArray"> < ...

The mobile view of the homepage slider is not appearing correctly

.main-slider-img > img{ width: 100%; } .main-slider-content { left: 15%; margin-top: -146px; position: absolute; top: 50%; } .main-slider-content > h2{ line-height: 50px; padding ...

Alert the host about any updates

I am currently working on an ASP.NET application that is hosted by a C# application using WebBrowser. The ASP.NET application runs within the C# application environment. My challenge lies in finding a way to notify the C# application when certain events, ...

What are the steps to halt background uploads?

Is there a way to stop an upload when I click on a button, even if it is still uploading in the background? Here's the code snippet: $(".imageCancel").click(function() { $(".upload_target").attr("src","#"); //iframe } ...

showing sections that collapse next to each other

I am currently designing a portfolio website using HTML, CSS, and vanilla JavaScript. I have implemented collapsing sections that expand when clicked on. However, the buttons for these sections are stacked vertically and I want to place them side by side. ...

Center a form on the page by adjusting its width and height dimensions

As a newbie to web development, I'm struggling with positioning my form at the center of the content. The form has a width of 930px and its height ranges between: min-height: 450px; max-height: 860px; I have tried different methods but haven't ...