Shifting elements in an array using Javascript

I am working with two arrays, one containing numbers and the other containing objects of the same length:

var a = [2, 0, 1], b = [obj1, obj2, obj3];

My goal is to rearrange the items in array 'b' based on the positions of the numbers in array 'a'.

If possible, I would prefer a solution using jQuery.

Any suggestions on the most efficient way to achieve this?

Appreciate any help. Thank you

Answer №1

If you want to achieve this, there isn't a built-in auto function available but you can utilize the array map method to obtain the desired outcome.

var customOrderByArray = function(order, data) {
  return order.map(function(position) {
    return data[position];
  });
};

var orderSequence = [2, 0, 1];
var dataArray = ['item1', 'item2', 'item3'];

var finalResult = customOrderByArray(orderSequence, dataArray);

console.log('final result:', 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

Different approaches to transforming jQuery code into functional AngularJS code

I am a beginner in AngularJS and I'm looking to implement functionality for a login page similar to the one you see when you click the 'Forgot Password' link: Would it be more appropriate to use a directive instead of a controller for this ...

What could be causing JQuery Clip to malfunction?

I'm currently exploring the clip function in JQuery to see how it works. Despite my efforts, I'm facing difficulties in getting the function to operate correctly. My intention is to make the image shrink to nothing within a second. Below is a sni ...

What is the formula to determine if x is greater than y and also less than z?

I need help determining if a number falls within the range of greater than 0 but less than 8 using JavaScript. Can anyone assist me with this? Here is my attempt at it: if (score > 0 && score < 8) { alert(score); } ...

problems with loading jquery and jquery UI conditionally

This code snippet demonstrates how to load jQuery from a CDN, falling back to a local version if needed: <script src="//ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script> <script>!window.jQuery && document.write( ...

Using Mongoose to Implement the Repository Pattern in Node.js

As a newcomer to node.js with a background in .net, I am interested in applying some of the design patterns I used with c#.net. However, I am encountering challenges due to the differences in object-oriented nature between c# and JavaScript. Specifically, ...

How can I use JavaScript fetch to retrieve data from a JSON file based on a specific value?

I am looking to extract specific values from a JSON array based on the ID of elements in HTML. How can I achieve this? [ { "product": "gill", "link": "x.com", "thumbnail": "gill.jpg ...

What strategies can be employed to enhance the natural movement of dots on my HTML canvas?

Check out my code pen here I'm looking for feedback on how to make the movement of the canvas dots more fluid and liquid-like. I've experimented with restricting the direction for a certain number of renders (draw()), which has shown some impro ...

The word "yargs" will not activate a command within a script

I have a NodeJs script that requires parsing command line arguments. Here is the code I have written: import yargs from "yargs"; import { hideBin } from 'yargs/helpers'; //.... yargs(hideBin(process.argv)).command('--add-item ...

I encountered a SyntaxError that reads "Unexpected token instanceof" while using the Chrome Javascript console

I find it quite surprising that the code below, when entered into the Chrome JavaScript console: {} instanceof Object leads to the error message displayed below: Uncaught SyntaxError: Unexpected token instanceof Could someone kindly explain why this ...

Utilizing Angular's File Upload feature with Glyphicon icons

Has anyone tried to open a local file using bootstrap glyphicon? I found this example at https://jsfiddle.net/JeJenny/ZG9re/, but it doesn't seem to work. Does anyone have any ideas on how to make this approach work with images like glyphicon? main.h ...

Guide on dynamically setting values for two indexes in ng-options using Angular.js

Can someone help me with this issue? I am trying to use two indexes ($index, $parent.$index) in the ng-options object with Angular.js. Below is my code explanation. <tr ng-repeat="d in days"> <td>{{d.day_name}}</td> <t ...

Guide to attempting an asynchronous function again in JavaScript with a time delay

I've been facing a challenge while trying to retrieve a record from a database. The issue of race conditions often leads to situations where the record might not be available when attempting the initial fetch. How can I implement retry logic to overco ...

What is the best way to combine two arrays of objects with varying values for the same key, and add a new object to the mix?

I have two arrays: arr1 = [ { "OwnershipNumber": 0, "ID": null, "Name": "Contractor LLC", "ContrEmployeeTypeId": 0, "ContactEmail": "", "ContactPhone": "", "VeteranEmployeeMilitaryAffiliation": "", "SocialSecurityNumber": ...

In TypeScript, maximize the capabilities of JavaScript modules by utilizing the import extension

Incorporating the dynamo-cache package from NPM into my TypeScript project has been a bit of a challenge. Essentially, this module introduces a new method to the AWS.DynamoDB.DocumentClient: AWS.DynamoDB.DocumentClient.prototype.configCache = function(con ...

"Enhance your PHP/Laravel skills by learning how to insert a new array element into a

I need to find a way to efficiently add a new element to a PHP array. Is there a shortcut to accomplish this without iterating over all the elements? [ "A": ["id": 12, "name": "test1"], "B": ["id&q ...

Converting CommonJS default exports into named exports / Unable to load ES module

I've encountered an issue while creating a Discord bot with discord.js using TypeScript. When attempting to run the resulting JavaScript code, I'm facing an error that states: import { Client, FriendlyError, SQLiteProvider } from 'discord.js ...

Save the chosen column value from an Excel spreadsheet into an Array by utilizing column letters in C# Excel Interop

As I work with Excel to import records into the program I am developing, my usual method involves retrieving data from Excel and storing it in an array using column indexes. Here's how I usually do it: Excel.Range xlRange = xlWorksheet.UsedRange; str ...

The code is functioning properly and executing without issues, yet I am puzzled as to why an error message is appearing in the console stating "Uncaught TypeError: Cannot read properties of null (reading 'style')"

Hey there, I'm new to the world of JavaScript and trying my hand at creating multiple modals that pop up. Everything seems to be working fine when opening and closing each modal, but I keep encountering an error message in the console (Uncaught TypeEr ...

Setting up web pack with flag-icon-css integration

I have successfully set up a webpack project using https://github.com/teroauralinna/webpack-guide. Now, I am looking to integrate https://github.com/lipis/flag-icon-css into my project. To do so, I followed these steps: npm install flag-icon-css --save T ...

What is the best way to retrieve certain fields from a Firestore database using Next.js?

Is there a way to access a specific field in a document using the user's uid as its name? I am utilizing useAuthState from react-firebase-hooks to retrieve the user's credentials (uid). https://i.sstatic.net/t1xGL.png This code snippet allows me ...