What is the best way to arrange an array of data based on the order specified in another

Despite my extensive search efforts, I have not been able to find a solution that meets my exact requirements. My question is: How can I sort an array based on the predefined order of another array?

For example-

const array1 = [
    {
        name: "1"
    },
    {
        name: "2"
    },
    {
        name: "3"
    }
]

const array2 = ["3", "1"]

I need to rearrange array1 according to this custom order:

const array = [
    {
        name: "3"
    },
    {
        name: "1"
    },
    {
        name: "2"
    }
]

In this case, the values from array2 should appear at the beginning of array1. I am seeking assistance in achieving this functionality.

Although I have made multiple attempts, the results have not been as expected-

const sortMarkets = (array: ArrayTypes[], sortArray: string[]) => {
  return [...array].sort(
    (a, b) => sortArray.indexOf(a.name) - sortArray.indexOf(b.name)
  )
}

console.log(sortMarkets(array, ag));

The output I received was-

[{
  "name": "2"
}, {
  "name": "1"
}, {
  "name": "3"
}]

Your help would be greatly appreciated.

Answer №1

To ensure proper sorting of unknown items, it is necessary to assign a distinct value. A high value in this scenario will push the item to the end of the list.

const
    array = [{ name: "1" }, { name: "2" }, { name: "3" }],
    ag = ["3", "1"],
    sortMarkets = (array, sortArray) => {
        const getOrder = name => (sortArray.indexOf(name) + 1) || Number.MAX_VALUE;
        return [...array].sort((a, b) => getOrder(a.name) - getOrder(b.name));
    };

console.log(sortMarkets(array, ag));
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

When comparing the .indexOf with the value of another array, it is essential to keep in mind that there are actually two criteria for sorting. The first criterion is for elements from the other array to be prioritized over the rest, and the second criterion is for these priority elements to be ordered based on their positions in the other array. Prior to comparison, it is crucial to add an additional check to determine whether the items being compared should belong to different sections (top or bottom).

const array1 = [
    {
        name: "1"
    },
    {
        name: "2"
    },
    {
        name: "3"
    }
];
const array2 = ["3", "1"];
array1.sort((a, b) =>
  (array2.includes(b.name) - array2.includes(a.name))
  || (array2.indexOf(a.name) - array2.indexOf(b.name))
);
console.log(array1);

To ensure compatibility with TypeScript, consider casting booleans to numbers prior to subtraction.

(Number(array2.includes(b.name)) - Number(array2.includes(a.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

What is the process for using AJAX and PHP to upload an image file?

I'm facing an issue where I want to insert an uploaded image into a database with user details for a profile picture. The output I receive currently shows {"current_field":null,"field_count":null,"lengths":null,"num_rows":null,"type":null}. How can th ...

The functionality of Google Maps' WatchPosition feature seems to be malfunctioning

One of the functionalities I'm working on involves tracking the user's position. First, I use getCurrentLocation to retrieve the user's location coordinates and then place a marker on the map to indicate their location (the marker variable i ...

Verify if there are DOM elements located within a DIV container, execute the functions associated with those elements sequentially

I am in the process of creating a game using HTML, CSS, and JavaScript. My focus right now is on manipulating DOM elements without relying on the canvas tag. The goal is to develop a pseudo graphical programming language, similar to the environment provide ...

How to prevent users from selecting certain options using angular's ng-options

As per the Angular documentation ng-options guidelines I tried to implement this piece of code: <select ng-model="model" ng-options="item.CODE as item.NAME disable when item.DISABLE for item in list" id="foo" name="foo" ng-change="change()"> Howe ...

Making a page jump with Javascript

Welcome! Let's dive into our question. Below you'll find my script and HTML code: My Script: const resultEl = document.querySelector('.allquotes'); const pageSize = document.querySelector('select[name="page-size"]') ...

Unable to retrieve data for the initial keystroke in jQuery autocomplete

I'm currently working on setting up jQuery autocomplete with a specific method involving a separate source function and an intermediary variable for data storage. My main goal right now is to successfully pass the data to the source part of the autoCo ...

Ways to discover various lists and add them to a separate collection

Having a .csv file with 1500 lines, each line containing data like this: CS105,A-,ENG101,A-,MATH101,A,GER,B,ENG102,B,CS230,B,MATH120,B,GER,A-,CS205,A,FREE,A-,GER,A-,CS106,B,CS215,B+,CS107,A,ENG204,A-,GER,A-,MATH220,B+,CS300,B,CS206,A,CS306,B+,GER,A-,FREE, ...

The $http.get request is successful only when the page is initially loaded for the first

Imagine this scenario: a user navigates to http://localhost:3000/all, and sees a list of all users displayed on the page. Everything looks good so far. However, upon refreshing the page, all content disappears and only raw JSON output from the server is sh ...

Parsing CSV files in Java can be done by splitting the data into arrays based on

Can anyone help me with this task? I have a CSV file that looks like this: column1$column2$column3 123$xyz$321 456$zyx$654 I need to parse it in Java into arrays or array lists based on columns/headers. For example: ArrayList column1 = [ ...

The transformation rotation applied in CSS must not have any impact on the styling of my span and paragraph

Snippet: .details-section{ background-color: rgb(83, 83, 83); height: 200px; } .icon-container{ border: 2px solid #c49b63; width: 90px; height: 90px; transition: 0.5s ease; } .box i{ font-size: 60px; color: black; margin-top: 13px ...

Modify the disabled attribute in an input element with a button click in Vue.js 2.x

With a loop generating multiple rows, each containing its own 'input' with description and action buttons, including an edit button that toggles the 'disabled' attribute. I'm struggling to figure out how to achieve this. I believe ...

Different ways to make jQuery attr() method include the attribute by using single quotation marks

I start by creating a div in memory: var video_div = document.createElement('div'); video_div.className = "vidinfo-inline"; Next, I define some variables: var key = "data-video-srcs"; var value = '{"video1":"http://www.youtube.com/watch?v ...

I encountered an issue where the IDs did not match while using an array to update the MYSQL database

Currently, I am facing an issue while looping through an array in node JS to update a MYSQL database. The problem arises because the array starts at 0, whereas my auto-incrementing database starts at 1. This misalignment offsets the entire database by on ...

Selenium's click() method in Python seems to experience issues when used within a script, but functions properly when used through

While working with python 3 selenium, I encountered an issue when trying to login to the Zomato website. When running a script, the login button was clicked but the dialog box did not open. However, when executing the same statements in the command line or ...

Counting the number of visible 'li' elements on a search list: A guide

In the following code snippet, I am attempting to create a simple search functionality. The goal is to count the visible 'li' elements in a list and display the total in a div called "totalClasses." Additionally, when the user searches for a spec ...

What methods can be used to control the URL and back button in a web application designed similar to an inbox in Gmail?

Similar Question: Exploring AJAX Techniques in Github's Source Browser In my application, there are essentially 2 main pages: The main page displays a list of applications (similar to an inbox) The single application page is packed with various ...

How can you use declaration to assign a static array in C to a dynamic array?

For instance, consider this scenario: int function(unsigned int input1, unsigned int input2){ int list[input1*input2]; return 0; } After compiling the code containing this snippet, there were no runtime issues as the array was successfully initialize ...

Transforming pictures with a click

How can I make the image change when it's clicked on? I tried using this code but it's not working. <image id="s" src="s.jpg" onclick="reaction()" ></image> function reaction() { var replace=d ...

How can dynamic arrays be displayed in C programming?

I'm a bit puzzled about whether I am correctly printing my dynamic array. I am parsing an input file that looks like this: x 6 9 15, My objective is to store the values 6, 9, and 15 into an array named x. This is working as expected. I have allocate ...

Creating an express route for updating with various parameters: a step-by-step guide

I am trying to make an update to a specific attribute in a JSON object by using the fetch PUT method. I have set up a put function that takes in 2 URL parameters app.put('/trustRoutes/:id/:item', (req, res){ So far, I have been able to update t ...