Process for arranging an array according to the sorting sequence of another

Using two arrays in a Highcharts "series" parameter, for example:

X = [25, 100, 50, 12]
Y = [50, 12, 100, 25]

The sequence of X and Y corresponds to the chart's Y value. When sorting X in ascending order, Y's order should match by becoming:

X = [12, 25, 50, 100]
Y = [25, 50, 100, 12]

A more sophisticated approach is needed rather than just using a basic sorting algorithm simultaneously on both arrays. Creating a data structure that links the values in these arrays together would allow for efficient sorting of one array with respect to the other.

The challenge lies in finding an object or data structure that can store and retrieve these two arrays together for integration into Highcharts. One concern is that plain JavaScript objects may not guarantee maintaining the order of elements, so it's important to consider alternative approaches.

Answer №1

To organize an array based on a custom sort order, you can create an array that contains the indexes of the desired sort sequence. Then, you can apply this sort order to any array you choose:

let arr1 = [25, 100, 50, 12]
let arr2 = [50, 12, 100, 25]

// define the sort order array based on arr1
let sort_order = Array.from(arr1, (_, i) => i).sort((a,b) => arr1[a] - arr1[b])

let arr1_sorted = sort_order.map(i => arr1[i])
let arr2_sorted = sort_order.map(i => arr2[i])

console.log(arr1_sorted, arr2_sorted)

Answer №2

Consider the alternative approach of generating an object with a and b properties for each item, sorting this array of objects, and then separating them back into their individual arrays:

const A = [25, 100, 50, 12];
const B = [50, 12, 100, 25];
const arr = A.map((a, i) => ({ a, b:B[i] }));
arr.sort((item1, item2) => item1.a - item2.a);
const [newA, newB] = arr.reduce(([newA, newB], { a: itemA, b: itemB }) => {
  newA.push(itemA);
  newB.push(itemB);
  return [newA, newB];
}, [[],[]]);
console.log(newA, newB);

Although this method may appear more functional, your original implementation, while simplistic, could potentially be faster for large inputs as it avoids the creation of intermediary arrays and objects.

Answer №3

Your initial concept isn't as terrible as you might think - just organize one array and rearrange the other without considering its contents. Nonetheless, I do agree that there is a more efficient way to approach this task in terms of organizing and identifying your data.

Considering that your two arrays are essentially pairs of {a, b}, you can consolidate all the data into a single array:

const consolidatedData = [{a: 25, b: 50}, {a: 100, b: 12}, {a: 50, b: 100}, {a: 12, b: 25}];

From here, it becomes straightforward to sort the array based on either key using a sorting function:

// Function to sort items by a specified key
const sortByKey = key => {return (itemA, itemB) => itemA[key] > itemB[key]};

consolidatedData.sort(sortByKey("a"));
// The array is now sorted with "a" keys in ascending order
consolidatedData.sort(sortByKey("b"));
// The array is now sorted with "b" keys in ascending order

If you need to separate the array back into two individual arrays, simply utilize Array.map():

const aValues = consolidatedData.map(item => item.a);
const bValues = consolidatedData.map(item => item.b);

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

Fastify route handler failing to start after onRequest hook is executed

I am currently working on a fastify application that needs to capture the raw body of post requests for authentication purposes. After extensive research, I discovered that fastify does not have native support for this feature. The solutions I found online ...

Javascript textbox and submit button

Is there a way to generate a text box with a submit button and save the input into a JavaScript variable? ...

What is the best way to display information from an array that is nested within an object retrieved from an API using

I am attempting to display data from . Using axios to fetch data from the API, I encounter an issue when trying to map through the received data as it is an array inside an object. This results in an error: TypeError: this.props.colors.map is not a funct ...

Arranging uneven lists in ascending order according to the values in the third column of the first row of each list

I have a CSV file where rows are grouped together based on the shared address. These groups typically consist of 1 to 10 rows each. My task is to sort these groups according to the date found in the fourth column of the first row within each group. Below ...

Retrieve the contents of the browser's DOM from within an Android operating system runtime

Imagine a typical login page similar to the one depicted below: https://i.stack.imgur.com/SF1Bd.jpg To interact with the HTML elements within the DOM, we can utilize either jQuery or conventional JavaScript like so: https://i.stack.imgur.com/e5aQZ.png ...

Struggling with sending intricate model to controller via ajax request

I've encountered an issue where my model is not updating properly when I click a button. Despite logging the data in the razor file and confirming that it's correct, the controller method receives an empty model. Below is the onclick method bein ...

Interactive HTML5 canvas: Dragging and dropping multiple items

I'm currently working on a project that involves allowing users to drag and drop multiple objects within a specified area. To achieve this, I am utilizing the html5 canvas tag. While the functionality works smoothly when dragging and dropping a single ...

Contrast data from two arrays and create a fresh array

I have two arrays that may or may not share similar values const arrayOne = [orange, red, black, blue, yellow] const arrayTwo = [blue, purple, white, red] Working with react, I aim to use useEffect to identify and return the unique elements when a change ...

Search for specific parameters in an array and retrieve them

I have been attempting to sift through an array of data retrieved from my API, but unfortunately, the data remains unfiltered. I suspect that it might be due to the way I implemented my method or perhaps my params are not being returned correctly. Below ar ...

Unable to retrieve data from the JSON object

I'm struggling to extract the data value from a JSON object. Let me share my code snippet: var ab_id = $( "#ab_id" ).val(); $.ajax({ type: 'GET', contentType: 'application/json', url: 'edit_account.php', ...

Could anyone provide an explanation of the current situation in this section of the code?

I am currently working on a piece of code that looks like this: ruter.get('/', async function (_, res) { const [categories, items] = (await Promise.all([ db.query('SELECT * FROM categories'), db.query('SELECT * FROM invento ...

Tips for clearing a textbox value in JQuery after a 5-second delay

I attempted the following: <script type="text/javascript"> $(function() { $("#button").click( function() { alert('button clicked'); // this is executed setTimeout(function() ...

Utilize Meteor-tabular to effortlessly export data with convenient HTML5 export buttons

Currently, I am utilizing the tabular package to display data from a collection in a table format. However, when attempting to export the data using html5 export buttons with the button (csvhtml5), only the length of data visible in the table is exported, ...

JavaScript Slider for Color Selection

In my slider, I have added a .images class along with buttons for previous and next. To set the colors, I have used JavaScript to define an array like this: let colors = ['red', 'green',]; Currently, clicking the next-button displays ...

recognizing individuals when a particular action is taken or when there is a disruption

Just starting to explore node.js I currently have a PHP/Laravel cms alongside a basic Nodejs game server that generates numbers in a loop To connect my PHP backend with Nodejs, I utilize Socketio and employ Socketio-JWT for user identification On the cl ...

Encountering a challenge when attempting to upgrade to Angular 9: Issue with transitioning undecorated classes with DI migration

As I transition from Angular 8 to Angular 9, I encounter an error during the step related to transitioning undecorated classes with DI. While attempting to migrate, I faced an issue with undecorated classes that utilize dependency injection. Some project ...

Include parameters for a pagination system

I have a script that fetches data from my database and generates pagination. Everything is working fine, but now I want to include a conditional statement to differentiate the user level as New, Current, or Renewing client. I've already set up some s ...

Is there a way to create a new prettyphoto window by clicking on a link within the original prettyphoto window?

I have an HTML table that is dynamically constructed on the server side using AJAX. The table is displayed using prettyphoto, everything works fine up to this point. However, the last column of the table contains a link that should open an image using pret ...

Browserify does not provide access to the require function in the browser environment

I am currently in the process of developing a web application using node.js along with express. My goal is to leverage Browserify in order to expose my local modules to the browser. Here is the structure of my application: ├── app.js ├── lib ...

Utilize React to reduce, replace, and encapsulate content within a span element

I have a Map that receives JSON data and generates a list item for each value. Then, I modify specific parts of the strings with state values. const content = { "content": [ { "text" : "#number# Tips to Get #goal#" ...