Fastest method for arranging an array depending on a different array

Here are two arrays, how can I quickly sort one array based on another?

var MainArray = [{
  guid: '24c2b868-8f4d-4113-a537-f8e7f57bb88b',
  info: 'photo 1'
}, {
  guid: '27e910cf-ba4c-412c-9faf-e7db5f058639',
  info: 'photo 2'
}, {
  guid: '66fc9e12-1c0a-447c-81c8-2f3a4bf0608c',
  info: 'photo 3'
}, {
  guid: 'f2afa8a9-6666-44d5-b360-8e7b8fb27c2e',
  info: 'photo 4'
}, {
  guid: '6d670044-9d3e-4c48-ba2b-5ec3e0c6be0f',
  info: 'photo 5'
}];




var newArray = [{
  id: 1,
  name: 'name1',
  guid: '6d670044-9d3e-4c48-ba2b-5ec3e0c6be0f'
}, {
  id: 2,
  name: 'name2',
  guid: 'f2afa8a9-6666-44d5-b360-8e7b8fb27c2e'
}, {
  id: 3,
  name: 'name3',
  guid: '66fc9e12-1c0a-447c-81c8-2f3a4bf0608c'
}, {
  id: 4,
  name: 'name4',
  guid: '27e910cf-ba4c-412c-9faf-e7db5f058639'
}, {
  id: 5,
  name: 'name5',
  guid: '24c2b868-8f4d-4113-a537-f8e7f57bb88b'
}];

I need to sort the new Array based on the guid of the MainArray, what's the best way to achieve this?

Answer №1

Create an object that references the index in the main array and sorts based on that

// object to hold index reference
var obj = {};

// loop through and store index reference in object
MainArray.forEach(function(v, i) {
  obj[v.guid] = i;
});

// sort based on the index
newArray.sort(function(a, b) {
  return obj[a.guid] - obj[b.guid];
});

var MainArray = [{
  guid: '24c2b868-8f4d-4113-a537-f8e7f57bb88b',
  info: 'photo 1'
}, {
  guid: '27e910cf-ba4c-412c-9faf-e7db5f058639',
  info: 'photo 2'
}, {
  guid: '66fc9e12-1c0a-447c-81c8-2f3a4bf0608c',
  info: 'photo 3'
}, {
  guid: 'f2afa8a9-6666-44d5-b360-8e7b8fb27c2e',
  info: 'photo 4'
}, {
  guid: '6d670044-9d3e-4c48-ba2b-5ec3e0c6be0f',
  info: 'photo 5'
}];



var newArray = [{
  id: 1,
  name: 'name1',
  guid: '6d670044-9d3e-4c48-ba2b-5ec3e0c6be0f'
}, {
  id: 2,
  name: 'name2',
  guid: 'f2afa8a9-6666-44d5-b360-8e7b8fb27c2e'
}, {
  id: 3,
  name: 'name3',
  guid: '66fc9e12-1c0a-447c-81c8-2f3a4bf0608c'
}, {
  id: 4,
  name: 'name4',
  guid: '27e910cf-ba4c-412c-9faf-e7db5f058639'
}, {
  id: 5,
  name: 'name5',
  guid: '24c2b868-8f4d-4113-a537-f8e7f57bb88b'
}];

var obj = {};

MainArray.forEach(function(v, i) {
  obj[v.guid] = i;
});

newArray.sort(function(a, b) {
  return obj[a.guid] - obj[b.guid];
});

console.log(newArray);

Answer №2

To enhance your code, consider utilizing a mapping system that links GUID values to corresponding information:

var PhotoArray = [ { guid : '24c2b868-8f4d-4113-a537-f8e7f57bb88b',info : 'photo 1'},
                  { guid : '27e910cf-ba4c-412c-9faf-e7db5f058639',info : 'photo 2'},
                  { guid : '66fc9e12-1c0a-447c-81c8-2f3a4bf0608c',info : 'photo 3'},
                  { guid : 'f2afa8a9-6666-44d5-b360-8e7b8fb27c2e',info : 'photo 4'},
                  { guid : '6d670044-9d3e-4c48-ba2b-5ec3e0c6be0f',info : 'photo 5'}
                   ];

var InfoArray = [{id : 1,name : 'name1',guid:'6d670044-9d3e-4c48-ba2b-5ec3e0c6be0f'},
               {id : 2,name : 'name2',guid:'f2afa8a9-6666-44d5-b360-8e7b8fb27c2e'},
               {id : 3,name : 'name3',guid:'66fc9e12-1c0a-447c-81c8-2f3a4bf0608c'},
               {id : 4,name : 'name4',guid:'27e910cf-ba4c-412c-9faf-e7db5f058639'},
               {id : 5,name : 'name5',guid:'24c2b868-8f4d-4113-a537-f8e7f57bb88b'}];

var mapper = {};

for (var j = 0; j < PhotoArray.length; j++) {
  mapper[PhotoArray[j].guid] = PhotoArray[j].info;
}

InfoArray.sort(function(x,y){return mapper[x.guid].localeCompare(mapper[y.guid]);})

Answer №3

Pranav C Balan's solution is effective, but here is an alternative approach to tackling the problem.

// Iterate over MainArray as it is already sorted
let sortedArr = MainArray.map((mainArrObject,i) => {

// Filter each object in newArray based on MainArray index
 return newArray.filter(newArrObject => {
  return newArrObject.guid == MainArray[i].guid
 })[0]

})


console.log(sortedArr)

var MainArray = [{
  guid: '24c2b868-8f4d-4113-a537-f8e7f57bb88b',
  info: 'photo 1'
}, {
  guid: '27e910cf-ba4c-412c-9faf-e7db5f058639',
  info: 'photo 2'
}, {
  guid: '66fc9e12-1c0a-447c-81c8-2f3a4bf0608c',
  info: 'photo 3'
}, {
  guid: 'f2afa8a9-6666-44d5-b360-8e7b8fb27c2e',
  info: 'photo 4'
}, {
  guid: '6d670044-9d3e-4c48-ba2b-5ec3e0c6be0f',
  info: 'photo 5'
}];

var newArray = [{
  id: 1,
  name: 'name1',
  guid: '6d670044-9d3e-4c48-ba2b-5ec3e0c6be0f'
}, {
  id: 2,
  name: 'name2',
  guid: 'f2afa8a9-6666-44d5-b360-8e7b8fb27c2e'
}, {
  id: 3,
  name: 'name3',
  guid: '66fc9e12-1c0a-447c-81c8-2f3a4bf0608c'
}, {
  id: 4,
  name: 'name4',
  guid: '27e910cf-ba4c-412c-9faf-e7db5f058639'
}, {
  id: 5,
  name: 'name5',
  guid: '24c2b868-8f4d-4113-a537-f8e7f57bb88b'
}];

let sortedArr = MainArray.map((mainArrObject,i) => {
 return newArray.filter(newArrObject => {
  return newArrObject.guid == MainArray[i].guid
 })[0]

})

console.log(sortedArr)

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

Is there a way to access the values that have been dynamically updated by JavaScript

Is it possible to parse an HTML page using the org.w3c.dom package? For example, let's take a look at . This webpage contains a counter that is updated by JavaScript. However, when trying to retrieve a value from: <div class='counter_field&ap ...

Generate a vector3 with a defined direction

I have a challenge at hand where I am looking to create a 2D flow field in three.js based on a working example I found in p5.js. The original source code for reference is as follows: var inc = 0.1; //Increment of noise var yoff = 0; var scl = var; //Scale ...

Why does the <select> dropdown flash when I select it?

Currently utilizing Angular 1.3 and Bootstrap 3.3.x CSS without the JS functionality. There is also an interesting animated GIF embedded within. <div class="form-group"> <div class="col-lg-3"> <label clas ...

What is the reason for the exclusion of square brackets in the reduce()

My current code: var isValid = function(s) { let arr = [...s]; arr.reduce((acc, cur) => { console.log(`arr in reduce: ${arr}`); console.log(`acc: ${acc}`); console.log(`cur: ${cur}`); if ((acc && cur) ...

Incorporating and utilizing the HTML5-captured image as a point of reference

I understand that all I need to do to achieve this is insert <input type="file" id="photo" accept="image/*;capture=camera"> However, my lack of coding skills has caused issues with actually grabbing and using the image selected/taken by the user. ...

pg-promise received an error due to an incorrect parameter being passed in for options

I have been working on transitioning my files from utilizing the pg package to the pg-promise package. Initially, everything was functioning correctly with the original pg solution I had in place. However, upon switching to pg-promise and referencing the d ...

Step-by-step guide on generating a numpy array while iterating through a loop

I currently have a numpy list that contains arrays (a two-dimensional list): db = [ch1, ch2, ch3, ch4, ch5, ch6, ch7, ch8, ch9, ch10, ch11, ch12, ch13, ch14, ch15, ch16] My goal is to apply operations to these arrays as shown below: for i in db: new ...

The process by which Expressjs determines the appropriate error handler to execute when multiple error handlers are present

I've been wondering, how does Express decide which error handler to call (next(err)) when there are multiple error handlers in place? ...

Tips for transferring backend information to show up as options in a multiselect dropdown menu (Jsfiddle link included)

Here is a reference to a fiddle link -->> https://jsfiddle.net/etfLssg4/ In the fiddle, users can select multiple dropdown items. The dropdown values are initialized with Lisa and Danny as the default items. These default selections are displayed in ...

What is the best way to run asynchronous Mocha tests (NodeJS) sequentially?

In regards to the NodeJS Mocha testing framework, I have a question. It appears that the default behavior is to begin all tests and then handle async callbacks as they are received. For async tests, I am interested in running each test after the async po ...

Using jQuery on the client-side to interact with a MongoDB database

Currently, I'm in the process of developing a basic example application to gain experience with using MongoDB. My goal is to create a single web page that can interact with a local MongoDB server by adding and removing content dynamically through jQue ...

How can we configure Node and Express to serve static HTML files and ensure that all requests are routed to index.html?

Currently, I am developing a single-page web application using Node alongside Express and Handlebars for templating. The project is running smoothly with the index.html file being served from a standard server.js script: var express = require('expre ...

React Native: Issue with TextInput vanishing within View container

Currently, I am diving into the world of React Native by following along with a book that teaches how to create a to-do app. However, my progress has hit a roadblock due to an error/bug I encountered on IOS (not sure if it also affects Android since I have ...

Troubleshooting Issues with Implementing JavaScript for HTML5 Canvas

I've encountered an issue with my code. After fixing a previous bug, I now have a new one where the rectangle is not being drawn on the canvas. Surprisingly, the console isn't showing any errors. Here's the snippet of code: 13. var can ...

Sending an array of objects as a parameter to a stored procedure in SQL

I am working with 2 tables: payment (payment_id, otherCosts, GarageCosts) spareparts (payment_id, sparepartId, sparePartQty) In the payment table, the payment_id is autogenerated. In my C# asp.net application, I have an array of objects like this: { sp ...

Adding a dynamic class to a single element in Vue JS and subsequently removing it from its siblings

I recently started learning Vue and I have a JavaScript code snippet that looks like this: var app = new Vue({ el: '#app', data: { nav1: true, nav2: false, nav3: false }, methods: { activatedThis: ...

Do not delay, MongoJS function is ready to go!

I have a function set up in my Express JS endpoint that uses 'await' to retrieve data from a Mongo DB using Mongo JS. Function:- async function getIntroducer(company){ const intro = await dbIntro.collection('introducers').findOne({c ...

The compatibility issue between styled-components and create-react-library is causing some functionality to

Upon attempting to import styled-components into a create-react-library module, I encountered an error message: Error: 'typeOf' is not exported by node_modules\react-is\index.js, imported by node_modules\styled-components\dist ...

Is there a way to verify if a user taps outside a component in react-native?

I have implemented a custom select feature, but I am facing an issue with closing it when clicking outside the select or options. The "button" is essentially a TouchableOpacity, and upon clicking on it, the list of options appears. Currently, I can only cl ...

The state remains consistent when utilizing useContext

hello I am currently working on creating a menu toggle in React using the useContext hook. I have set up a variable with an initial value of false, but used createContext and useState to initialize it as true. // Implementing useMenu Context import React, ...