Modify the index of an array based on another array using JavaScript

Looking to adjust the positions of elements in array a based on their locations in array b.

const a = [4,3,2,1,5];
const b = [1,2,3,4,5];

console.log(a)  [1,2,3,4,5]

Answer №1

If you're looking to sort array a based on the elements in array b, you can achieve this using the following code:

a.forEach((element, i) => {
    // Find the index of a[i] in array b
    const index = b.indexOf(a[i])
    
    // Swap the elements
    const temp = a[index];
    a[index] = a[i];
    a[i] = temp;
})

Answer №2

To achieve sorting, one can utilize the second array as an index. In case this approach fails with actual data, it is recommended to include a small set of data to pinpoint the issue.

const
    x = [4, 3, 2, 1, 5],
    y = [1, 2, 3, 4, 5];

x.sort((left, right) => y[left - 1] - y[right - 1]);

console.log(...x);

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

Leverage WooCommerce API in conjunction with Express.js

Here's the code snippet I've been working on: const express = require('express'); const router = express.Router(); const WooCommerceAPI = require('woocommerce-api'); const WooCommerce = new WooCommerceAPI({ ...

What is the best way to import my json information into an HTML table and customize the rows as radio buttons using only Javascript?

I am facing an issue with processing a JSON response: var jsondata = dojo.fromJson(response); There is also a string that I am working with: var jsonString = jsondata.items; The variable jsonString represents the JSON data in the file: jsonString="[ ...

Enhance User Experience with ngDialog Modal's Multi-pane Feature for Angular

Looking at the ngDialog example, they showcase a modal with multiple 'panes' that can be scrolled through: . After going through the ngDialog guide, I couldn't find a straightforward way to achieve this. Any suggestions on how to add a butt ...

Conceal the legend in Highcharts using Python script with Django

Need some assistance with a Django and Highcharts.js project I'm working on. Objective: hide the legend in a Highcharts chart from my views.py script. In my views.py file, I've successfully plotted various charts but struggling to hide the lege ...

Exploring table iteration in Angular 7

I am looking to create a table with one property per cell, but I want each row to contain 4 cells before moving on to the next row... This is what I want: <table> <tr> <td> <mat-checkbox>1</mat-checkbox& ...

What is the best way to accomplish this task with promises (using the Q library)?

I am currently working on an app using express.js and mongodb. My goal is to fetch all posts if the database is available, otherwise an error will be thrown. I am utilizing the Q package for promises, but I am struggling to implement the desired functional ...

Incorporating tags into the react-select component

https://i.sstatic.net/Fsknq.pngI am still a beginner in the world of react-js. Currently, I am experimenting with the following: https://i.sstatic.net/4Ggoz.png This is what I have attempted so far: const options = [ { value: 'chocolate', ...

What is the best way to prevent regex from detecting character matches while Ctrl, Shift, or other keys are pressed?

My task was to create a code that detects when a key is pressed and counts the number of characters entered. I opted to use var regex=/[a-zA-Z0-9]/;, but I discovered that pressing Enter, Shift, Ctrl, or Alt also triggered the count. Here's the cruci ...

Personalize your iOS keyboard to display the numeric keypad

Currently, I am developing a hybrid app that requires the display of a numeric keyboard with both dot and comma functionalities on iOS. Although I have tried using the pattern [0-9] with type set as number, it seems to work fine on Android devices but unfo ...

Transferring elements into a freshly allocated array of structures

I am attempting to duplicate a structure into an array of structures. The structure I have is a graph structure that contains a field with a dynamically allocated array of vertices called vlist and an integer that stores the number of vertices in the v ...

How can I add additional query parameters to the original request in node-http-proxy?

While attempting to enhance the original request in my node-http-proxy by adding new query parameters, directly tweaking req.query like this does not seem to work: app.all(path, function (req, res) { req.query.limit = 2; apiProxy.web(req, res, { t ...

React-Redux Project: Issue with React components not displaying properly, only the Parent directory gets rendered

Luckily, I managed to resolve the webpack build issues successfully. Nevertheless, every time I execute 'npm start' (webpack-dev-server), it serves the parent directory of this file. The reason behind this behavior remains unclear. -I've cr ...

The text entered in the textbox vanishes after I press the submit button

When a user selects a value in a textbox and clicks the submit button, the selected value disappears. <div class="panel-body" ng-repeat="patient in $ctrl.patient | filter:$ctrl.mrd"> <form> <div class="form-group"> ...

Incorporating the non-typescript npm package "pondjs" into Meteor applications using typescript files

Implementing the Pondjs library into my project seemed straightforward at first: meteor npm install --save pondjs However, I'm encountering difficulties when trying to integrate it with my Typescript files. The documentation suggests: In order ...

Hugo: Utilizing template variables within JavaScript files

Within my Hugo website, the baseUrl configuration is set to: website.com/variable. If an image element is present in a .html file (such as < img src="/images/image.png" >), the baseUrl is appended resulting in the final URL being: website. ...

Uncharted Territory: Exploring asynchronous loops with async await and Promise.race?

Currently, I am involved in a project that requires brute forcing a PDF password. To achieve this task, I am using PDF.js to verify the password and implementing promise.race to execute parallel functions for efficient performance. This is how I have str ...

NestJS encounters issues when trying to resolve the dependencies of the AuthServices

Following a prior issue with JWT_MODULE_OPTION, I have encountered an old problem that I thought was resolved. However, fixing the old problem seems to have created a new one related to JWT. Once again, I am unable to compile: Nest can't resolve dep ...

When utilizing JSON data in node.js, the .find() method may return undefined

I am currently working on a node server and my goal is to display JSON data when a specific ID is clicked. I have configured a dynamic URL that will retrieve the data of the clicked video using parameters and then compare it with the data in the JSON file ...

Warning in React js: [eslint] srcApp.js Line 2:8 - The variable 'person' is declared but not utilized

[![I need assistance with this problem. Whenever I try to resolve it, I consistently encounter the same error on Line 2:8: 'person' is defined but never used - no-unused-vars.][1]][1] ...

Choose the child nodes upon selecting the root node

I am trying to implement a 2-level material-ui treeview where selecting the root node should automatically select all child nodes as well. Does anyone have suggestions on how to achieve this with material-ui treeview? For more information, please visit ma ...