arranging nations based on their names using javascript/vue

I am currently utilizing the country-data library found at country-data.

loadCountries() {
  return require("country-data")
  .countries.all.filter(country => country.name)
  .map(country => ({
    label: country.name,
    value: country.alpha3
  }));
},

Unfortunately, I am facing difficulties in sorting countries by name in my select component.

Any help or advice would be greatly appreciated. Thank you!

Answer №1

After reading through the documentation

It seems that utilizing the sort method instead of filter would be more appropriate for your situation.

var items = [
  { name: "Edward", value: 21 },
  { name: "Sharpe", value: 37 },
  { name: "And", value: 45 },
  { name: "The", value: -12 },
  { name: "Magnetic", value: 13 },
  { name: "Zeros", value: 37 }
];
items.sort(function (a, b) {
  return a.value - b.value;
});

For your specific scenario, the following could be effective:

loadCountries() {
  return require("country-data")
  .countries.all.sort((a, b) => a.name - b.name)
  .map(country => ({
    label: country.name,
    value: country.alpha3
  }));
}

Additionally, another option is to utilize localeCompare

loadCountries() {
  return require("country-data")
  .countries.all.sort((a, b) => a.name.localeCompare(b.name))
  .map(country => ({
    label: country.name,
    value: country.alpha3
  }));
}

Answer №2

Consider using the Array.prototype.sort() method instead of filter:

<template>
    <div></div>
</template>

<script>
let countries = require("country-data").countries;

export default {
mounted() {
    let sortedCountries = countries.all
    .sort((c1, c2) => {
        if (c1.name < c2.name) return -1;
        if (c1.name > c2.name) return 1;
        return 0;
    })
    .map(country => {
        return {
            name: country.name,
            alpha3: country.alpha3
        };
    });

    console.log("sortedCountries: ", sortedCountries);
  }
};
</script>

<style scoped>
</style>

The result will display the countries sorted alphabetically by name:

https://i.sstatic.net/6AfvU.png

Update:

Another option is to use String.prototype.localeCompare(compareString[, locales[, options]]), which allows for specifying language and customizing function behavior.

<script>
let countries = require("country-data").countries;

export default {
mounted() {
    let sortedCountries = countries.all
    .sort((c1, c2) => c1.name.localeCompare(c2.name))
    .map(country => {
        return {
            name: country.name,
            alpha3: country.alpha3
        };
    });

    console.log("sortedCountries: ", sortedCountries);
  }
};
</script>

This method will give you a slightly different ordered list:

https://i.sstatic.net/lGsze.png

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

Button Hover Effect: Transition with Style

I am trying to implement a one-second transition from the default color scheme to the hover color for a Button element in Material UI. I am using the transitions.create(props, options) method as described in this article: https://medium.com/@octaviocoria/c ...

Advancing the utilization of custom Angular input fields

I've developed a unique Angular input element that utilizes a textarea as its primary input field. Is there a way for me to pass along the enter key event to the main form? ...

What is the best way to create an associative array using jQuery and then send it through AJAX to be parsed by PHP?

Is there a way to create an associative array in jQuery and send it via ajax to a php page for processing? Here is an example of what I am trying to achieve... // jQuery if($something == true) { data[alt] = $(this).attr('alt'); data[sr ...

Guide on importing CDN Vue into a vanilla Typescript file without using Vue CLI?

In the midst of a large project that is mostly developed, I find myself needing to integrate Vue.js for specific small sections of the application. To achieve this, I have opted to import Vue.js using a CDN version and a <script> </script> tag ...

Initial part before entering the line of input

Is there a way to add a prefix to input blocks similar to how Python does it? E:\Users\foobar\Downloads\KahootTest1>py Python 3.7.4 (tags/v3.7.4:e09359112e, Jul 8 2019, 19:29:22) [MSC v.1916 32 bit (Intel)] on win32 Type "help", ...

The function nested within a constructor that includes `this.route` is not assigning it as an array

this.routeHandler = function () { let stations = ['KSFM', 'KPWM'] let coordinates = []; let allCoords = []; if (Array.isArray(stations) == true) { for (let i = 0; i < fetchRoute().length; i++) { fo ...

Discovering the specific DOM element that has been clicked using only JavaScript

Looking to enhance my HTML document with interactivity, I wanted to achieve a feature where clicking on a div element would display its respective id. I attempted the following approach: window.onload = function() { associateIds(); clicked(); } fu ...

Encountering issues when attempting to create a service worker in a Vue.js application using Workbox's injectManifest feature

I'm attempting to utilize vue.js's capabilities for progressive web apps by creating a customized service worker using workbox. However, every time I try to build the app, I encounter the following error: AssertionError [ERR_ASSERTION]: swSrc mus ...

Obtaining a worldwide JavaScript variable through AJAX JSON query

Hello, I have encountered an issue while using this code for my AJAX JSON request. When attempting to make jsonObj a global variable and then console.log() it, the debugger console shows that it is always coming up as undefined. To explain my question fur ...

Checkbox malfunctioning when trying to add values after being checked

I have successfully completed a calculation system project using JavaScript. Everything works well, the calculations are accurate and taxes are included properly. However, I am facing an issue where the tax is not being included when I click on the checkbo ...

Change ES6 JavaScript to ES5 standard

Is there a way to transform this code snippet from other questions into ES5 format? I am attempting to extract data from a JSON array. var match = function(query, input) { return input.filter(function(entry) { return Object.entries(query).every(fun ...

Using Node JS to query data from MySQL and filter a column based on an array of objects

I am dealing with a column in my database that can either be null, contain a single integer, or multiple integers separated by commas. I need to filter specific rows based on this column. However, instead of using a search string, I have an array that coul ...

JQuery: Issue with closing modal on certain popups

I have configured a popup that is associated with 6 different products. While it functions correctly for the first product, it does not seem to work properly for the rest. <script> //var modal = document.getElementById("m ...

Is it possible to retrieve calculated data from a child component and pass it to the parent component?

Is there a way to transfer computed data from a child component to a parent component? Currently, I am passing data from the parent to the child first and then I would like to utilize the computed property (data) in the parent component. This is crucial as ...

Show the time in hours and minutes (00:00) while rounding off seconds to the nearest minute

I need the time to always display with leading zeros when less than 10. For example, if a task took 3 hours, 7 minutes, and 33 seconds, it should be shown as 03:08. Currently, I have the buttons disabled after they are clicked to prevent restarting the ti ...

AngularJS: Enabling unidirectional binding for select option to model

Utilizing a dropdown to display client names. Users have the ability to choose an existing client, which will then update the scope property: Controller Setting up the initial selection. if($scope.clients.length > 0) $scope.existingClient = $scope.cl ...

The array.slice() method fails to work properly when I try to start it from any index other than 0

I am currently working with an array called $scope.results which contains 8 objects. I have also created a custom simple pagination and a function called selectAll() that I'm trying to get to work together. Please refrain from suggesting the use of b ...

There was an issue locating the moment/ts3.1-typings/moment module

Encountering an ERROR after updating Angular version: Could not resolve moment/ts3.1-typings/moment in node_modules/ngx-daterangepicker-material/ngx-daterangepicker-material.d.ts ...

I need assistance in locating an error; the error message states that $ is not defined and an object is expected

Issue with $ not being defined, object expected.. I am trying to verify if all sets of radio buttons are checked when a button is clicked! Please help. <script type="text/javascript> $(document).on('click', 'form', function () { ...

The useEffect() method used without any cleanup function

It is mentioned that, "Every time our component renders, the effect is triggered, resulting in another event listener being added. With repeated clicks and re-renders, numerous event listeners are attached to the DOM! It is crucial to clean up after oursel ...