Arranging an Array of Objects according to the Index in another Array

I am faced with a challenge involving two arrays. The first array consists of unique IDs:

idArray = ["56f4cf96dd2ca7275feaf802",
"56f4cf96dd2ca7275feaf7b7",
"56f4cf96dd2ca7275feaf805",
"56f4cf96dd2ca7275feaf7ac"]

The second array contains objects, including titles and corresponding IDs:

stories = [{"title": Story2, id = "56f4cf96dd2ca7275feaf7b7"},
{"title": Story4, id = "56f4cf96dd2ca7275feaf7ac"},
{"title": Story1, id = "56f4cf96dd2ca7275feaf802"},
{"title": Story3, id = "56f4cf96dd2ca7275feaf805"}]

I need to figure out a way to sort the second array based on the index order in the first array. This task is ideally performed using lodash due to possible scalability issues with larger arrays.

So far, I have attempted to extract indexes from the first array as follows:

var sortArray = _.toPairs(idArray)

[ [ '0', 56f4cf96dd2ca7275feaf802 ],
[ '1', 56f4cf96dd2ca7275feaf7b7 ],
[ '2', 56f4cf96dd2ca7275feaf805 ],
[ '3', 56f4cf96dd2ca7275feaf7ac ] ]

Despite experimenting with various combinations of _.map() and _.sortBy(), I'm unable to achieve the desired result which is:

desiredResult = [{"title": Story1, id = "56f4cf96dd2ca7275feaf802"},
          {"title": Story2, id = "56f4cf96dd2ca7275feaf7b7"},
          {"title": Story3, id = "56f4cf96dd2ca7275feaf805"},
          {"title": Story4, id = "56f4cf96dd2ca7275feaf7ac"}]

Answer №1

In my opinion, the sort solution is not very efficient, especially considering the potential for larger arrays in the future. The sort function can be at best an O(2n) operation, with two indexOf operations per cycle adding up to another O(2n^2). I suggest the following alternative approach that can outperform the sort method when dealing with large arrays.

var stories = [{"title": 'Story2', id : "56f4cf96dd2ca7275feaf7b7"},
{"title": 'Story4', id : "56f4cf96dd2ca7275feaf7ac"},
{"title": 'Story1', id : "56f4cf96dd2ca7275feaf802"},
{"title": 'Story3', id : "56f4cf96dd2ca7275feaf805"}],

    idArray = ["56f4cf96dd2ca7275feaf802",
"56f4cf96dd2ca7275feaf7b7",
"56f4cf96dd2ca7275feaf805",
"56f4cf96dd2ca7275feaf7ac"],

ordered = idArray.reduce((p,c) => p.concat(stories.find(f => f.id == c)) ,[]);

console.log(ordered);

This approach has only O(n^2) complexity.

Answer №2

Sorting can be achieved without the need for any external libraries using the built-in method Array.sort()

var tales = [{"name": 'Tale2', id : "56f4cf96dd2ca7275feaf7b7"},
{"name": 'Tale4', id : "56f4cf96dd2ca7275feaf7ac"},
{"name": 'Tale1', id : "56f4cf96dd2ca7275feaf802"},
{"name": 'Tale3', id : "56f4cf96dd2ca7275feaf805"}];

var idList = ["56f4cf96dd2ca7275feaf802",
"56f4cf96dd2ca7275feaf7b7",
"56f4cf96dd2ca7275feaf805",
"56f4cf96dd2ca7275feaf7ac"];

var sortedTales = tales.sort(function(a, b){
return idList.indexOf(a.id) - idList.indexOf(b.id);
});

sortedTales.forEach( item => { console.log(item) });

Answer №3

Give this a shot

const indexesToIds = {};

for (let j = 0; j < idsArray.length; j++)
    indexesToIds[idsArray[j]] = j;

posts.sort(function(x, y){return indexesToIds[x.id] - indexesToIds[y.id];});

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

Why does the setInterval function only run once before stopping?

Can someone assist me with this issue? The stop button only invokes clearInterval() once - what is causing this problem in the code? var startButton = document.querySelector("#start"); var stopButton = document.querySelector("#stop"); window.addEventLi ...

What is the process of transferring JavaScript code to an HTML file using webpack?

I am looking to display an HTML file with embedded CSS, fonts, and JS (not linked but the content is inside). I have the CSS and fonts sorted out, but I am struggling to find a solution for the JavaScript. My project is based on Node.js. ...

Listening for changes made easy - AngularJS

Hey everyone, I'm experimenting with Angular JS and would love to hear some insights from all you experts out there :D What I'm currently working on is creating my own localization code. Yes, I know there are existing libraries available, but I ...

Having trouble accessing the data I'm setting in a separate component using the Context API

Currently working on my own project and I've encountered a problem while using the Context API. It's my first time using it. The issue I'm facing is that I can't seem to console.log the data I'm setting. I'm trying to create ...

How to retrieve JSON data from ASP.NET code-behind file and pass it to JavaScript

I'm facing an issue with my webstatic method that converts my dataset into JSON. I want to retrieve this JSON in my JavaScript file, but unfortunately nothing is appearing in my div. As a newcomer to ASP.NET and JSON, I must be doing something wrong h ...

Creating a cascading select menu based on the selected value of another select menu

I am in the process of creating a menu that displays two lists for regions: one <select> for selecting the region and another <select> for choosing from available municipalities within that region. I have set up a <form> and I utilize Jav ...

Do the incoming ajax data trigger any "if" conditionals?

Very new to coding, so forgive me if this is a simple question... I'm currently developing a web application where clicking a "Search" button triggers an ajax request to fetch data, which is then used to populate a table using the jQuery .DataTable m ...

Display loading animation until Google Maps is fully loaded - Utilizing AngularJs

Is there a way to check the readiness of Google Maps before displaying it? I'd like to show a preloader block while the Google Maps is loading. Here is the factory code I am using: var map = false; var myLatlng = new google.maps.LatLng(48.6908333333 ...

Resetting a form in React JS: A step-by-step guide

How can I clear the input values in a React JS form upon clicking Reset? class AddFriendForm extends Component { constructor(props) { super(props) this.state = { firstname: '', lastname: '', } } render() { c ...

The error TS2339 is indicating that there is no property called myProperty on the type SetStateAction<User>

I'm encountering a TypeScript error while working with React that's leaving me puzzled: <html>TS2339: Property 'subEnd' does not exist on type 'SetStateAction&lt;User&gt;'.<br/>Property 'subEnd' d ...

Using Python's for loop to iterate through a two-dimensional index

I'm facing a challenge that seems simple, but I'm struggling to figure out how to tackle it using Python. Within my Python for loop, I have a unique value defined during each iteration. Now, I want to access the value of the NEXT or PREVIOUS uni ...

Struggling to display a collection of items in React

Below is the code snippet : import React, { Component } from 'react'; import axios from 'axios'; import _ from 'lodash'; import Loader from './Loader'; export default class Main extends Component { constructor(p ...

Using the geonames web service to access up-to-date information on earthquakes

Is there a way to utilize the longitude/latitude coordinates of a location to access a specific webservice with parameters like north, south, east, and west? Any suggestions or insights would be appreciated. Thank you! Discover Recent Earthquakes Webser ...

Tips on obtaining the data count from using the $.get method

Here is the code I'm currently working with: $.get('getstatsAccepted' + tickerid, {tickerid: tickerid}, function(data) { alert(data.length); }, 'json'); I am interested in obtaining the numbe ...

Enhancing speed and efficiency when zooming in on various elements using React

Issue: The zoom functionality in my React application becomes sluggish when I have over 20 components rendered. The app needs to handle zooming with thousands of components being rendered. Current zoom implementation: Currently, in my application, there ...

Where can I find the @types for a specific lodash package?

Seeking to utilize a specific function from lodash - assignin. I have successfully installed lodash.assignin and incorporated it into my project: import assignIn = require('lodash.assignin'); However, when compiling, an error occurs: "error TS2 ...

Can we divide an animation in Three.js according to a model's individual parts?

Recently delving into the world of three.js, I have encountered a project with specific requirements: Load a humanoid gltf model Play various animations on the model Stop or play animation for only the head part of the gltf model without altering animatio ...

Tips for eliminating additional white space within a bootstrap row

I'm having trouble removing the extra space on my website while using Bootstrap 5. I've tried various Bootstrap classes like pr-0, mr-0, p-auto, m-auto but none of them seem to work. I also attempted using CSS margin-right: 0; but that didn' ...

Tips for accessing the firebase user's getIdToken method in Next.js after a page reload

Currently, I am developing a Next.js project and implementing user authentication using Firebase's signInWithPhoneNumber method for phone number verification. After successful verification, I receive a Firebase user with the getIdToken method to retri ...

Creating a countdown timer for a specific date and time using web technologies

I'm looking to create a timer countdown that is set to a specific date and time, such as June 1st at midnight. The code should display the remaining time until that date or time. ...