Arrange the array of items according to the order specified in a separate array

Related Questions:
JavaScript - Sorting an array based on another array of integers
Sort an array in JavaScript based on another array

If I come across an array structured like this:

['one', 'four', 'two']

And then there is this other array:

[{
  key: 'one'
},{
  key: 'two'
},{
  key: 'four'
}]

Is there a way to reorganize the second array so that its key value aligns with the order of the first array? Specifically, I'm aiming for:

[{
  key: 'one'
},{
  key: 'four'
},{
  key: 'two'
}]

Answer №1

By utilizing the sort() function, we are able to achieve this by providing it with a custom comparison function. This particular function must yield one of three values based on the comparison between a and b:

If a comes before b in order, we return -1

If a is deemed equal to b, we return 0

If a follows b in order, we return 1

To illustrate, we can create a function like so:

function compareValues(a,b){
    var indexA = array.indexOf(a['identifier']);
    var indexB = array.indexOf(b['identifier']);
    if(indexA < indexB) {
        return -1;
    } else if(indexA > indexB) {
        return 1;
    } else {
        return 0;       
    }
}

This function takes the objects defined within your array, determines their location in the array, which serves as the reference for comparison. It then contrasts the indices and produces the necessary output.

To implement this, we supply the function to the sort() function as follows:

dataList.sort(compareValues)

where dataList denotes the array undergoing sorting.

You can observe a demonstration of this technique in action here, showcasing the second object in your array being showcased both prior to and following the execution of the sorting function. http://jsfiddle.net/Abc123/

Answer №2

Here is my interpretation:

function rearrangeArray(order_array, array_to_rearrange) {
    var rearranged_array = [], 
        length = array_to_rearrange.length,
        length_copy = length,
        index, current_item;

    for (; length--;) {
        current_item = array_to_rearrange[length];
        index = order_array.indexOf(current_item.key);
        rearranged_array[index] = current_item;
    }

    //modify the array
    Array.prototype.splice.apply(array_to_rearrange, [0, length_copy].concat(rearranged_array));
}

Example usage:

var order_array = ['one', 'four', 'two'],

    array_to_rearrange = [
        {key: 'one'},
        {key: 'two'},
        {key: 'four'}
    ];

rearrangeArray(order_array, array_to_rearrange);

console.log(array_to_rearrange); //logs [{key: 'one'}, {key: 'four'}, {key: 'two'}];

Check out the demo here: http://jsfiddle.net/joplomacedo/haqFH/

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 best location to initialize a fresh instance of the Firebase database?

Is the placement of const db = firebase.database() crucial in a cloud function script? For instance, in a file like index.ts where all my cloud functions are located, should I declare it at the top or within each individual function? const db = firebase. ...

Implementing automatic hyperlinking of words to a webpage address with the help of jQuery

I have a JavaScript array structured as follows: let associativeArray = []; associativeArray["1"] = "First"; associativeArray["2"] = "Second"; associativeArray["3"] = "Third"; My goal is to utilize jQuery to automatically link certain words from the arra ...

React Router - Implementing a <Redirect> element rather than a list of child components

Here is the code snippet I am working with: import { Redirect } from 'react-router-dom'; import QPContent from '../QPContent'; class AnswerContainer extends Component { constructor(props) { super(props); this.state = { ...

I encountered an unexpected obstacle while reloading my Next.js application with animejs. The error message reads: "SyntaxError: Unexpected token 'export'." This unwelcome occurrence took place during the

Encountering an error with animejs when reloading my Next.js app: An unexpected token 'export' is causing a SyntaxError. This issue occurred during the page generation process. The error originates from file:///Users/.../node_modules/animejs/lib ...

Creating dependent dropdowns using Laravel Inertia Vue: A step-by-step guide

In my AddressController, I have a function called loadCity along with other CRUD functions: public function loadCities(Request $request) { $provinceId = $request->province_id; $cities = Province::where('province_id' ...

Using AngularJS filters to narrow down content within an ng-repeat

Check out this JSON code example: $scope.info = [{"name":"Category1", "data":[{"name":"Item1"}, {"name":"Item2"}]}, {"name":"Category2", "data":[{"name":"Item3"}, {"name":"Item4"}]}]; I have utilized ng-repeat to display the list and ...

Animating a div using a changing scope variable in AngularJS

As a newcomer to Angular, I am looking to add animation to a div element using ng-click within an ng-repeat loop. Here is what I have attempted: app.js var app = angular.module( 'app', [] ); app.controller('appController', function($ ...

Issue: Unable to link to 'options' as it is not recognized as a valid attribute of 'chart'

Here is a sample component code snippet: import { Component, OnInit, Input } from '@angular/core'; import { Observable } from 'rxjs/Rx'; @Component({ selector: 'chart', templateUrl: 'app/comps/chart.html', ...

Choose a random cell in Jquery every second

I am searching for a method to choose one div out of sixteen and change its CSS backgrounds. This selection needs to occur every second, so a new div is selected from the group each second. I am struggling with implementing the "every second" functionalit ...

Encountered an issue with the ProgressPlugin: TypeError - Unable to access property 'tap' of an undefined element

Encountering a Problem with npm run build Here's the issue at hand Compiling client E:\ui\sheraspace_ui\node_modules\webpack\lib\ProgressPlugin.js:223 compilation.hooks.addEntry.tap("ProgressPlugin", entryAdd ...

Converting MongoDB Queries to MySQL in Node: A Step-by-Step Guide

I am currently facing a challenge where I need to migrate my app's database from mongoDB to mysql. The application was initially developed using node.js, but I encountered an issue with the "Create table" query while attempting the conversion process. ...

Relationship between multiple Mongoose instances linking to a single entity

Having an issue regarding mongoose and relationships. My "Athletes" collection has the following schema: var athletesSchema = mongoose.Schema({ name : String, regionName : String, age : Number, overallScore : Number, scores : { ordinnal : String, ...

What steps do I need to take to execute a browserify-ed application in NodeJS?

I have an interesting challenge on my hands - I need to modify a sizable JavaScript codebase to be compatible with NodeJS. The current code follows the CommonJS style and utilizes a gulp build process involving browserify and deamdify. While I am somewhat ...

Is there a way to continuously run jQuery code or reset it?

Can you help me create a loop that will continuously run this script after it finishes executing, repeating the process indefinitely? I want to keep running this code over and over again. This script is using jQuery version 3.5.1 // Title var title1 ...

Close to completing the AngularJS filter using an array of strings

I'm currently working on developing a customized angular filter that will be based on an array of strings. For instance: $scope.idArray = ['1195986','1195987','1195988'] The data that I aim to filter is structured as fo ...

Eliminating the shared characters from two arrays of characters

For a class assignment, we have specific constraints that need to be followed. We are unable to use ArrayList and must complete the manipulation with arrays. Let's assume we have two arrays: char[] firstArray -> {'a','b'}; cha ...

Issue with applying projection to graticule in D3 and Three.js: unable to execute projection on graticule

My current project involves creating 3D graticules using three.js. The process starts by constructing a mollweide projection graticule in SVG with D3, followed by extracting the graticule path points and converting them to three.js vectors. However, the r ...

Instead of using a checkmark, consider using step numbers with Mui Stepper's Completed StepIcon

I'm currently utilizing Mui Stepper from [email protected] within a React project. Despite my efforts to search on platforms like Stackoverflow and Github, I have been unable to find a solution for displaying the step number upon completion inst ...

Share the hyperlink to a webpage with someone else

In my SQL command, I have a unique feature that retrieves the complete URL value of the current page: [##cms.request.rawurl##]. This code returns the entire URL. I need to send this address to another page and load it into a special div called "load-fac". ...

JavaScript issue: Submitting form does not trigger the associated function

I am currently in the process of learning JavaScript as part of my university course, and I have encountered an issue where my function is not being called. I am seeking to gain a better understanding of why this problem is occurring. Summary The situati ...