Home > Enterprise >  How to sort an array based on selected language? (ReactJS)
How to sort an array based on selected language? (ReactJS)

Time:12-17

I want to sort the list of country names based on the language the user selects.

By default, this list is sorted according to the English alphabet. But considering that every language has a different and distinct alphabet, in some cases it becomes difficult for the user to find the desired result. I want this list to be sorted alphabetically for each language that the user selects.

I use ReactJS and react-i18next to translate my application.

class Example extends React.Component {
    
    constructor(props) {
        super(props);
        this.state = {
            // example country list
            locations: [
                {
                    "id": 2,
                    "name": "Ã…land Islands",
                    "code": "AX"
                },
                {
                    "id": 1,
                    "name": "Afghanistan",
                    "code": "AF"
                },
                {
                    "id": 3,
                    "name": "Albania",
                    "code": "AL"
                },
                {
                    "id": 39,
                    "name": "Burkina Faso",
                    "code": "BF"
                },
                {
                    "id": 43,
                    "name": "Canada",
                    "code": "CA"
                },
                {
                    "id": 220,
                    "name": "Switzerland",
                    "code": "CH"
                },
                {
                    "id": 234,
                    "name": "Turks and Caicos Islands",
                    "code": "TC"
                },
                {
                    "id": 242,
                    "name": "Uzbekistan",
                    "code": "UZ"
                },
                {
                    "id": 243,
                    "name": "Vanuatu",
                    "code": "VU"
                },
                {
                    "id": 246,
                    "name": "Wallis and Futuna",
                    "code": "WF"
                },
                {
                    "id": 247,
                    "name": "Western Sahara",
                    "code": "EH"
                },
                {
                    "id": 248,
                    "name": "Yemen",
                    "code": "YE"
                },
                {
                    "id": 250,
                    "name": "Zimbabwe",
                    "code": "ZW"
                }
            ],
        };
    }

    sortCountryList = () => {
        // I got the selected language from localStorage. result: en || de || fr || ar
        let selected = localStorage.getItem("i18nextLng");

        let newLocations = this.state.locations;
        const collator = new Intl.Collator(selected, { sensitivity: "base" });

        // try to sort but not working in selected languages
        newLocations = this.state.locations.sort((a, b) => {
            return collator.compare(a.name, b.name);
        });

        console.log("location");
        console.log(this.state.locations);

        // sorted in english. But i need to sort base on selected language.
        console.log("newLocations");
        console.log(newLocations);

        this.setState((prevState) => ({
            locations: newLocations,
        }));
    }

    render() {
        return (
            <ul>
                {this.state.locations.map((location) => {
                    return (
                        <li key={location.id}>
                            {this.props.t(location.name)}
                        </li>
                    );
                })}
            </ul>
        );
    }

    componentDidUpdate(prevProps) {
        // withNamespaces: i18next.t
        if (this.props.t !== prevProps.t) {
            this.sortCountryList();
        }
    }
}

Result: enter image description here

CodePudding user response:

one way that comes to my mind, is sort like this below

 newLocations = this.state.locations.sort((a, b) => {
                return collator.compare(this.props.t(a.name), this.props.t(b.name));
            });

CodePudding user response:

You can use localCompare method to sort strings in any language.

const arr = ['b','a']

var locale = 'en' // English locale

var sortedArr = arr.sort(function(a,b) { return a.localeCompare(b, locale); });

French Locale

const items = ["réservé", "Premier", "Cliché", "communiqué", "café", "Adieu"];

items.sort((a, b) => a.localeCompare(b, "fr", { ignorePunctuation: true }));
// ['Adieu', 'café', 'Cliché', 'communiqué', 'Premier', 'réservé']

You can check Mozilla Doc

  • Related