JavaScript code for sorting a list of objects alphabetically according to a different list

I am looking to alphabetically sort a list of objects based on another list of characters and the 'name' property. Below is the sorting order I would like to use:

 const SortingArray = [['a','á','à','â','ä','å','ã'],['b'],['c','ç'],['d'],
                      ['e','é','è','ê','ë'],['f'],['g'],['h'],['i','í','ì','î','ï'],
                      ['j'],['k'],['l'],['m'],['n','ñ'],['o','ó','ò','ô','ö','õ'],['p'],
                      ['q'],['r'],['s','š'],['t'],['u','ú','ù','û','ü'],
                      ['v'],['w'],['x'],['y','ý','ÿ'],['z','ž']];

Here is the list that needs to be sorted:

var listToSort = [{name: 'Étape',code: 'c12'},{name: 'Abc',code: 'c14'},{name: 'Ûrter',code: 'c15'}
]

Answer №1

To achieve this, create a custom sorting function that determines the position of the first letter of each word in the SortingArray array. Here's a code snippet to help you get started:

    listToSort.sort((a, b) => {
        const aIndex = SortingArray.findIndex(charArray => 
            charArray.includes(a.name[0].toLowerCase())
        );
        const bIndex = SortingArray.findIndex(charArray => 
            charArray.includes(b.name[0].toLowerCase())
        );
        return aIndex - bIndex;
    });

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

Is there a way to use JavaScript or jQuery to identify if Firefox is blocking mixed content

Is there a way to detect when Firefox (or any browser) is blocking mixed content using JavaScript or jQuery? To learn more about Firefox's mixed content blocking feature, visit: The backstory: My company has an external vendor that handles the onli ...

Is there a specific reason why react-helmet does not automatically update the og meta tag?

I am currently working on generating dynamic og. Specifically, I have a detailed page featuring news on my website. When sharing a link to this page, it should generate the og data. Below is an excerpt of my code: <Helmet> <title>{info &a ...

What is the solution for resolving the error related to converting implicit any type to index type in TypeScript?

Can you help with fixing this issue? "How do I resolve the error: 'Element implicitly has an 'any' type because expression of type 'any' can't be used to index type?' " What could be causing this problem? Can you expla ...

A guide on transforming HTML into a variable using JavaScript

Having trouble converting HTML to a JavaScript variable. This is my HTML code: <div onclick="openfullanswer('2','Discription part','This is the code part');"> I want to create this HTML code dynamically, but I&apo ...

Personalizing the label of a select input using materialui

Working on customizing a select element using the "styled" method: const StyledSelect = styled(Select)` height: 2rem; color: #fff; border-color: #fff; & .${selectClasses.icon} { color: #fff; } & .${outlinedInputClasses.notchedOutl ...

Send data from input to controller without using $scope

I am encountering an issue with the code below. Typically, I would resolve this problem using $scope, but this time I have been asked to find a solution without utilizing $scope in the controller. I am implementing the "controller as" syntax for managing ...

What is the best location to create the content for a sidebar?

Currently in the process of building my new website using express. The layout consists of various "sections" such as a blog, project information, and more. I want to have a unique sidebar next to the main content for each section. For instance, in the "blo ...

Error: Trying to use Router without providing a middleware function. Please make sure to pass a valid middleware function while using Router

While working on my express application with MongoJS, I encountered an issue where despite returning a function, it was showing that an object has been returned instead. To address this, I made sure to include module.exports=router in my JavaScript file. H ...

Is it possible to update the content page without having to refresh the master page?

Our website features a Master page with main menu options and corresponding sub menus. When a user clicks on a main menu item, the relevant sub menus should be displayed. After clicking on a sub menu, the content page should update without having to refr ...

Error encountered when entering a value in the Material UI keyboard date picker

When I select a date by clicking on the calendar, it works fine. However, if I initially set the date to empty and then type in the date, it does not recognize the format and displays numbers like 11111111111111111111. This breaks the date format. If I sel ...

Which components can be interacted with in Protractor?

The element I am attempting to engage with utilizes the ng-sortable attribute and consists of a few draggable and sort-able divs. await viewTransaction.getEl('div#dragdrop-boundary').sendKeys(protractor.Key.ARROW_DOWN); Failed: element not inte ...

Working with double quotes within variable in JavaScript

I am currently working on dynamically creating HTML tags using JavaScript. Please take a look at the code snippet below: function getPhotosSuccess(data) { if (data.d.results.length > 0) { var response = data.d.results; var innerht ...

Typescript - Troubleshooting undefined error with static variables

My node API app is developed using express and typescript. The static variable of the Configuration Class is initialized with required configuration before starting the server. However, when I try to use this static variable in a separate TypeScript class ...

Issue with Bootstrap Carousel Interval Setting not Functioning as Expected

I recently added Twitter Bootstrap-Carousel to a website with the intention of using it to navigate through different sections of a module. However, I'm encountering an issue where setting the interval to false does not work as expected. When I set an ...

Cannot trigger a click event on nginclude in AngularJS

I have a question regarding including a new page using the nginclude directive. The click event defined in the included page is not working properly. Main Application: <div ng-app=""> <input type="text" ng-model="ss"/> <div ...

Pop-up message on card selection using JavaScript, CSS, and PHP

I have a total of 6 cards displayed in my HTML. Each card, when clicked, should trigger a modal window to pop up (with additional information corresponding to that specific card). After spending a day searching for a solution online, I've come here s ...

Execute the index.js file using the parameters specified in the mocha test suite

Within my index.js file, I am passing in specific arguments. // parameters var outFile = process.argv[2] || (() => {throw "missing argument outFile";})(); var templateName = process.argv[3] || (() => {throw "missing argument templateName";})(); My ...

What is the best way to incorporate PHP code within a JavaScript function?

Is it possible to dynamically append the uploaded file name to the list displayed in ('.list')? The challenge lies in passing $_FILES["fileImage"]["name"] as an argument to a separate JavaScript function for appending, especially since the PHP sc ...

Choosing the specific columns to be shown in the Kendo Angular grid

Will there be an interface available in the grid for users to select which columns are displayed, or is this a feature that will be introduced in the upcoming September release? ...

Incorporate Angular directives within a tailor-made directive

I just started using a fantastic autocomplete directive called Almighty-Autocomplete. However, I feel like it's missing some features. The basic structure of the directive is as follows: .directive('autocomplete', function () { var index ...