Tips for generating a list of sorted indexes by value within an object

In my project, I have multiple objects named stations, each containing a property called money.

stations[0].money = 2000
stations[1].money = 500
stations[2].money = 1200
stations[3].money = 2200

My goal is to create an array of station indexes (0, 1, 2, and 3 in this case) but arranged based on the amount of money each station has, sorted in ascending order. So the desired output should be:

var moneyArray = [1, 2, 0, 3]

I'm looking for the most elegant solution to achieve this result. Any suggestions?

Answer №1

To begin, create a regular array of indexes (ideally generated within a loop) and then organize it based on the values of each object in your stations array:

[0, 1, 2, 3].sort(function(ai, bi) {
    return stations[ai].money - stations[bi].money;
})

Answer №2

For more information, feel free to check out this resource: Sorting with map

// sample array for sorting
var items = [
        { price: 2000 },
        { price: 500 },
        { price: 1200 },
        { price: 2200 },
    ];

// create a new array with index and value pairs
var mapped = items.map(function (el, i) {
    return { index: i, value: el.price };
})

// sort the mapped array based on values
mapped.sort(function (a, b) {
    return a.value - b.value;
});

// reorder the original array based on sorted values
var result = mapped.map(function (el) {
    return items[el.index];
});

// extract the indices of sorted elements
var keys = mapped.map(function (el) {
    return el.index;
});

document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');
document.write('<pre>' + JSON.stringify(keys, 0, 4) + '</pre>');

Answer №3

To achieve this, one method is to utilize a Temp variable. Alternatively, if making modifications to the main data is feasible, then eliminating the temp variable is an option.

var stations = [{money :2000},{money :500},{money :1200},{money :2200}]

var tempArray = stations.slice();

tempArray.forEach(function (value, i) {
    value.index = i;
});

tempArray.sort(function(a, b){return a.money-b.money});

var finalResult = tempArray.map(function(a) {return a.index;});

document.write(JSON.stringify(finalResult));

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

Repairing the 'Uncaught TypeError: Cannot read property 'split' of undefined' bug in a Prestashop Module

Help! I'm encountering an issue with a Prestashop module, and the developer is unresponsive. Can anyone shed light on why I am seeing this error in the console? Thank you so much in advance! admin.js:57 Uncaught TypeError: Cannot read property ' ...

Encountering the error message 'XMLHttpRequest is not defined' while incorporating getServerSideProps() in NextJS

I'm currently exploring NextJS with SSR and encountering an error when trying to fetch data from a Spotify playlist using the spotify-web-api-js library. This issue only occurs when executing on the server side: error - ReferenceError: XMLHttpRequest ...

The execution of form validation and any following code is halted

I have an update form that is called inside a modal on my main page. Whenever I click on it, an XMLHttpRequest triggers the edit page containing the form with the stored data values. Everything seems to work fine except for the form validation and AJAX use ...

Issues with Angular's http get functionality not functioning as expected

I'm experimenting with an API on apiary.io and attempting to retrieve data from it using Angular, but I'm encountering issues with the call. The setup seems straightforward, so I'm not quite sure what's causing the problem: HTML: < ...

How to choose a javascript drop down using selenium?

Here is the HTML code for a JavaScript drop-down menu that contains various options, including "All Resumes". I am attempting to select this option using Selenium WebDriver: <div id="resume_freshness_container"> <div class="dropdown_small_wrapper ...

What steps should I take to create a plugin for a library if defining it as a peerDependency does not provide a specific implementation for me to work with?

Requirements for My Plugin: I'm currently in the process of developing a new plugin that is dependent on popularLibrary.js. Here are the key points about my plugin: It will not function properly if popularLibrary.js is missing. It is designed to wo ...

What is the best way to notify administrator users when their accounts have exceeded the timeout period?

Working on the website for our high school newspaper, I've encountered a recurring issue on the admin page. Users are getting logged out after creating an article due to a time limit constraint. To address this problem, my goal is to implement an aler ...

The onProgress event of the XMLHttpRequest is triggered exclusively upon completion of the file upload

I have a situation with my AJAX code where the file upload progress is not being accurately tracked. The file uploads correctly to the server (node express), but the onProgress event is only triggered at the end of the upload when all bytes are downloaded, ...

The perplexing aspect of why numpy arrays allow for slicing and converting values to integers, while lists of tuples do not, continues to baffle many

I'm attempting to extract the first and last values from a list of lists and convert them to integers. While I have found a solution, I find it a bit cumbersome and am curious if there's a more elegant way to achieve this. There are two methods ...

"Enhance your HTML table by selecting and copying cell values with a simple click and CTRL +

I stumbled upon a fantastic script for highlighting HTML table rows and it's working perfectly: I decided to modify the onclick event to onmouseover and included additional code to select a cell by clicking on it. Now I can select, check which one is ...

Is there a better approach to accomplishing this task using jQuery?

http://jsfiddle.net/bGDME/ My goal is to display only the selected content within the scope and hide the rest. The method I used feels a bit cumbersome. I'm open to suggestions on how to improve this. Any guidance would be greatly appreciated. Tha ...

Is forked processes included in node.js --max-old-space-size?

Currently, I am tackling out-of-memory errors in a node.js application by utilizing the --max-old-space-size parameter when launching node. I have set the size to 4096MB, which is the maximum as per https://github.com/nodejs/node-v0.x-archive/wiki/FAQ (I c ...

Exploring the concept of self in JavaScript

Exploring the concept of "self" magic, take a peek at this excerpt from nodejs (which is not complete). Socket.prototype.connect = function(options, cb) { ...... var self = this; var pipe = !!options.path; if (this.destroyed || !this._handle) { ...

Is it possible to author TypeScript modules in a format other than ES6?

Is it possible to utilize AMD for writing code? define([ 'hb!./some/file.hb' ], function(template) { // }) ...

The best practices for integrating Firebase with REST APIs

While searching for a tutorial on integrating REST APIs with Firebase, I came across numerous code snippets utilizing the curl method calls or other helper libraries. However, what I couldn't find were the basics - such as where to call these methods ...

Transforming Uint8Array into BigInt using Javascript

I've come across 3 different ways to convert a Uint8Array to BigInt, but each method seems to produce varying results. Can someone clarify which approach is correct and recommended? Utilizing the bigint-conversion library. The function bigintConversi ...

I am attempting to create a skybox, yet it seems like I am overlooking a crucial element

Currently, I am attempting to create a skybox but have encountered difficulties with various tutorials. Initially, I tried to use an array approach to pass parameters for the material based on a previous example, but it seems that the method has been updat ...

Placing the cursor on a newly created element is ineffective when the innerHtml is empty

https://codesandbox.io/s/nameless-feather-duk25?fontsize=14&hidenavigation=1&theme=dark In the code example above, I am trying to make a certain feature work. The concept is as follows: there is a contentEditable div element where text can be type ...

Is there a way to specify object keys in alignment with a specific pattern that allows for a variety of different combinations

I am seeking a way to restrict an object to only contain keys that adhere to a specific pattern. The pattern I require is: "{integer}a+{integer}c". An example of how it would be structured is as follows: { "2a+1c": { // ... } } Is there a ...

Persist the configuration settings of Data tables (such as ColReorder and ColVis plug-ins) by saving and loading them from a database

Does anyone know if it's possible to save and load the states of Data tables (such as ColReorder, ColVis plug-ins) to/from a database? I've tried implementing this, but I'm still facing difficulties. Below is my code for loading the states f ...