Tips for organizing an array to match another array?

Issue at hand: I am faced with a situation where I have an array of objects that need to be sorted in ASC DESC order based on one of the object keys. Following this, I also need to sort an array of strings in the same manner as the array of objects. For example:

arrayOfObjects = [{name:"john",number:6,food:"pizza"},
               {name:"david",number:2,food:"gulash"},
               {name:"margaret",number:7,food:"gugi berries"}]

arrayOfStrings = ['r1','r2','r3']

Each object in arrayOfObjects corresponds to a string in arrayOfStrings. For instance, John is associated with r1 and they are first in their respective arrays. However, when I sort by number, John gets moved to the second position. In this case, I want his corresponding string 'r1' to also move to the second position, along with David and Margaret's numbers.

The goal is to rearrange the arrayOfStrings in the exact order that the arrayOfObjects was sorted, regardless of the sorting criteria used for the objects.

Here is my sorting function :

dataArray.sort(dynamicSort(sortBy)); 
function dynamicSort(property) {
    var sortOrder = 1;
    if(property[0] === "-") {
        sortOrder = -1;
        property = property.substr(1);
    }
    return function (a,b) {
        if(direction=='asc'){
            var c = b;
            b=a;
            a=c;
        }
        var result = ( b[property] < a[property]) ? -1 : ( b[property]> a[property]) ? 1 : 0;
        return result * sortOrder;
    }
}

Answer №1

To efficiently organize your list, I recommend zipping it in the format [[item, description], ...], sorting based on the first element of each tuple, and then unzipping the list afterwards for easy access.

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

Access Vue.js data attribute in jQuery

Is there a way to extract the data-src attribute value from the following HTML code using Vue.js? <img id="some_id" :data-src = "some_path"> I attempted to assign this value to a variable using jQuery: var imgSrc = $("img:data(src)"); Unfortunat ...

My objective is to modify a JSON object based on the chosen value from a dropdown menu

Here is the code snippet I have created using HTML: <select style="width:100px;" data-nodrag ng-model="conditions" ng-change="changingCondition(this)"> <option value="and">and</option> <option value="or">or</option> & ...

Issue with React-Redux state not updating properly in setInterval()

I am encountering an issue with react-redux / react-toolkit. My state is called todos and it is populated with 3 items correctly, as shown in this image: https://i.sstatic.net/LThi7.png Below is the code of my todo slice: import { createSlice } from &apo ...

Having trouble with AJAX within AJAX not functioning properly?

Similar to the Facebook commenting system, I am aiming for comments to be appended to previous ones and displayed all at once. However, currently the comments only show up after the page is reloaded. Please Note: Each post initially loads with just two co ...

Using JavaScript to pass a value from an input field to a href attribute

I am currently working on a scenario where, upon clicking on an input field, the value is passed to a URL and the corresponding radio button is checked. This way, I can share the URL with someone else. Unfortunately, I have hit a roadblock in my progress: ...

Sending data to a Sheetlabs API using Axios

I'm currently collaborating with a service called Sheetlabs to transform a Google Sheet into a full-fledged API. Unfortunately, I'm struggling to find useful resources online apart from the Sheetlabs documentation, as it appears to be a relativel ...

Encountering an 'undefined' response when passing an array in Express's res.render method

After my initial attempt at creating a basic node app, I discovered that the scraper module was working correctly as data was successfully printed in the command window. Additionally, by setting eventsArray in index.js, I confirmed that Express and Jade te ...

What are the best practices for managing promises effectively?

Currently, in my Angular application, I am utilizing $odataresource for handling data retrieval and updates. The code snippet I am working with is as follows: var measure = $odataresource("http://windows-10:8888/ChangeMeasure/"); var myMeasure = measure ...

Avoiding the use of numbers in v-if in Vue.js

My website features a left menu that displays different content based on the selected menu's ID. However, I currently have === 0 and === 1 in the v-if statement, and I'm looking for a way to avoid manually inputting these numbers. <template& ...

I am curious as to why jQuery offers the done() method for promises, while the JavaScript promises documented by Mozilla do not. Is there a way to incorporate a done() method in vanilla JavaScript promises if needed?

What sets apart the Promises in Mozilla's JavaScript documentation (view API page) from those in jQuery's Promises (see API page)? It appears that Mozilla's promise only includes 2 methods: then and catch. On the other hand, jQuery's p ...

Seeking assistance in loading the webpage content when the button is clicked

<html> <body> <a href="samepage.php"><img src="button.png"></a> <div> //page content, database queries, calculations etc </div> </body> </html> I'm interested in loading the DIV content dynamicall ...

Having trouble with jQuery's find() function not working in conjunction with prev()?

I'm in need of some assistance because I think I may be approaching this the wrong way. Here is a link to the jsfiddle I have created: https://jsfiddle.net/m35o8jjL/2/ Below is the HTML code snippet: $( ".layered_subtitle_heading" ).click(function ...

Achieve top-notch performance with an integrated iFrame feature in Angular

I am trying to find a method to determine if my iframe is causing a bottleneck and switch to a different source if necessary. Is it possible to achieve this using the Performance API? This is what I currently have in my (Angular) Frontend: <app-player ...

Using JavaScript and the Firefox browser, learn how to easily highlight an element with Selenium-WebDriver

I am struggling with creating a valid function to highlight specific elements on a webpage. As a beginner in coding, I suspect that the issue may either be related to my environment setup or a lack of knowledge about JavaScript/Selenium features. I am wri ...

Can an array of finalized strings still be changed?

Let's say I have an array public static final String[] fooArray ={ Foo.a, Foo.b, Foo.c }; with Foo.a, b, and c being static final Strings. Is it possible to change the content of the array with fooArray[0] = "taco";, resulting in { taco, Foo.b, Foo ...

What is the importance of cloning React state before making changes or while working on it?

Someone advised me to always create a clone or copy of the react state before making any changes to it. const newState = [...this.state] newState.name = 'hardik' I'm still unsure about the reason behind this recommendation. Why shouldn&apos ...

Incorporating TWEEN for camera position animations: A complete guide

function adjustCameraPosition(newPosition, animationDuration) { var tween = new TWEEN.Tween( camera.position ) .to( newPosition, animationDuration ) .easing(TWEEN.Easing.Linear.None) .onUpdate(fun ...

JavaScript event listener 'click' not functioning properly

I'm facing an issue with a click event in a script that is associated with a specific div id. When I move the mouse within the div area and click (the cursor remains unchanged), the event listener does not activate. How can I make the div area clickab ...

Do I need to utilize getStaticProps along with JSON imports in Next.js?

Is it necessary to use getStaticProps in order to render static data from a JSON or typescript file, or can the data be imported without using getStaticProps? The documentation I read didn't provide a clear answer. projects.tsx const projects: [ { ...

Reading lines from a text file and storing them in a character array using a pointer

Hello! I am currently working on a program that executes commands from a text file. The issue I'm facing is that when I try to store the lines one by one into a char array, all arrays end up containing the last line from the text file. I'm not su ...