Combining two arrays in a sorted manner by their unique identifiers

Having two arrays of objects is quite common for me:

var parents = [
  { id: 77777, data: {}},
  { id: 88888, data: {}},
  { id: 99999, data: {}}
]


var children = [
  {
    belongTo: 77777,
    data: [
      { id: 111, data: {}},
      { id: 222, data: {}}
    ]},
  {
    belongTo: 99999,
    data: [
      { id: 333, data: {}}
    ]
  }
]

My ultimate goal is to combine parents and children into one comprehensive array:

var all = [
  { id: 77777, data: {}},
  { id: 111, data: {}},
  { id: 222, data: {}},
  { id: 88888, data: {}},
  { id: 99999, data: {}},
  { id: 333, data: {}}
]

In my quest to achieve this merge efficiently, I have experimented with various methods. Unfortunately, splitting or merging them together and then flattening the result always seemed overly complicated.

I wonder, what could be the simplest way to accomplish this merge?

Here's a method I've attempted (which proved ineffective):

children.map(function(child) {
  var parentIndex = parents.map(function(x) {return x.id}).indexOf(child.id)

  parents.splice(parentIndex + 1, 0, child.data)
})

[].concat.apply([], parents)

Answer №1

If you're looking to achieve this, nested loops are the way to go: http://codepen.io/xyz123/1/

let parents = [
  { 
    id: 11111,
    data: {}
  },
  { 
    id: 22222,
    data: {}
  },
  { 
    id: 33333,
    data: {}
  }
]

let children = [
  {
    belongTo: 11111,
    data: [{
      id: 444,
      data: {}
    }]
  },
  {
    belongTo: 33333,
    data: [{
      id: 555,
      data: {}
    },
    {
      id: 666,
      data: {}
    }]
  }
]
let allData = [];
parents.forEach((parent) => {
    allData.push(parent);
    children.forEach((child) => {
        if (child.belongTo === parent.id) {
            child.data.forEach((element) => {
                allData.push(element);            
            });                
        }
    });
});
console.log(allData);  

Answer №2

Give this a try

var adults = [{
    id: 12345,
    info: {}
}, {
    id: 67890,
    info: {}
}, {
    id: 54321,
    info: {}
}];

var minors = [{
    belongsTo: 12345,
    info: [{
        id: 111,
        data: {}
    }, {
        id: 222,
        data: {}
    }]
}, {
    belongsTo: 54321,
    info: [{
        id: 333,
        data: {}
    }]
}];

function combine(adults, minors) {
  var adultLength = adults.length,
      minorLength = minors.length,
      output = [];
  
  for (var i = 0; i < adultLength; i++) { 
    output.push(adults[i]);
    
    for (var j = 0; j < minorLength; j++) {
      if (adults[i].id === minors[j].belongsTo) {
        output = output.concat(minors[j].info);
      }
    };
  }
  
  return output;
}

console.log(combine(adults, minors));

Adjustment for your specific requirements

var adults = [{
    id: 12345,
    info: {}
}, {
    id: 67890,
    info: {}
}, {
    id: 54321,
    info: {}
}];

var minors = [{
    belongsTo: 12345,
    info: [{
        id: 111,
        data: {}
    }, {
        id: 222,
        data: {}
    }]
}, {
    belongsTo: 54321,
    info: [{
        id: 333,
        data: {}
    }]
}];

minors.forEach(function(child) {
  var parentIndex = adults.map(function(x) {return x.id}).indexOf(child.id);
  adults.splice(parentIndex + 1, 0, child.info)
})

adults = [].concat.apply([], adults)

console.log(adults);

Answer №3

By utilizing Higher Order Functions in conjunction with some ES6 features, we can achieve a more concise solution:

let merged = parents.map((parent) => {
  let data = children.filter((child) => child.belongTo == parent.id)
                    .reduce((acc, cur) => acc.concat(cur.data), [])
  return [parent].concat(data)
})

console.log([].concat(...merged))

Is there an opportunity for further refactoring?

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

Update the information within a specific DIV element

Is there a way to refresh content inside a div that is already on the same page, rather than being loaded from another page? For instance: <?php $this = 1; ?> <div id= "refresh_this"> <?php echo $this; ?> </div> ...

Keeping the Drawer open in Material-UI: What you need to know!

I am looking to create a collapsible sidebar feature in Material-UI where only the icons are displayed when collapsed. I have successfully implemented the Mini Variant Drawer for the basic sidebar functionality, but I'm facing an issue with maintainin ...

What changes should I make to the panUp function in Three.js orbit controls?

Currently, I am tinkering with adjusting the behavior of the panUp function in three.js' orbit controls. By default, this function moves the camera up and down along the y axis. However, I want to change it so that it moves in and out along the z axi ...

Discover the positions of the y-axis tick marks with d3.js

I have been working on creating an SVG visualization using d3.js (specifically version 3 of d3 in PowerBI) and I am encountering difficulties in aligning my data points and fixed lines with the correct y-axis tick markers. When there are 8 axis points, th ...

Unable to proceed, WISTIA upload frozen at 100% complete

I recently integrated the Wistia API for video uploads. Everything seemed to be working fine as per the Wistia documentation until I encountered an issue. After uploading a video file, the progress bar would reach 100%, but then an error was logged in the ...

generate a customized synopsis for users without storing any data in the database

In order to provide a summary of the user's choices without saving them to the database, I want to display it in a modal that has already been created. Despite finding some sources online, none of them have worked for me so far. Below is my HTML: &l ...

What is the reason why the "@wordpress/scripts" package does not produce the *.asset.php file when running "npm run build"?

I have been creating custom Gutenberg blocks using npm, webpack, and @wordpress/scripts. Everything was running smoothly until I encountered an issue with the block.json file. In order to use the block.json file, I discovered that I needed a block.asset.ph ...

Utilize the Feefo JSON data and convert it to a JavaScript array for rendering as an HTML

Currently diving into the world of Javascript and JSON, but feeling a bit overwhelmed by it all. Attempting to pull data from a JSON array, I've managed to reach this stage $(function(){ var $reviews = $('#reviews'); $.ajax({ ...

Utilizing React to connect with Metamask and share the signer across various contracts

I'm currently working on a solution for sharing signers across multiple JavaScript files. In my walletConnect.js file, I successfully connect to Metamask and retrieve an ERC20 token contract. async function connect(){ try{ const accounts = awai ...

What are the differences between Node's bcrypt and bcryptjs libraries?

When it comes to using bcrypt in Node, the abundance of libraries available can be overwhelming. Among the top packages on npm are bcrypt with 247k downloads per month bcryptjs with 337k downloads per month (any other options worth considering?) What s ...

The issue persists where Tailwind Inline color decorators are unable to function properly alongside CSS variables

In my current project using Tailwind CSS with CSS variables for styling, I have noticed a peculiar issue. The color previewers/decorators that usually appear when defining a color are not showing up in my class names. These previewers are quite helpful in ...

The custom font fails to load on a customized Material UI theme

In my React web application, I tried to implement a custom font by writing the following code: import React, { FunctionComponent } from 'react' import { createMuiTheme, MuiThemeProvider } from '@material-ui/core/styles' import SofiaPro ...

Creating a table with a static first column and vertical text positioned to the left of the fixed column

To create a table with the first column fixed, refer to this fiddle link: http://jsfiddle.net/Yw679/6/. You also need a vertical text to be positioned to the left of the fixed column in a way that it remains fixed like the first column. The disparities be ...

Error Encountered While Serializing Products in getServerSideProps in Next.js v14

I am using Next.js version 14.2.3 and I am currently trying to retrieve a list of products from Firestore by utilizing the getProducts function from @stripe/firestore-stripe-payments within getServerSideProps. However, I am facing a serialization error: ...

How can you retrieve a C# variable within JavaScript while using Selenium?

When working with the code below, I encountered an error stating "Linklocation is not defined". How can I properly access the variable within my JavaScript code? IWebElement link = driver.FindElement(By.LinkText("soemtext")); String linkLocation ...

Is there a way to set up an automatic pop-up for this?

Experience this code function AutoPopup() { setTimeout(function () { document.getElementById('ac-wrapper').style.display = "block"; }, 5000); } #ac-wrapper { position: fixed; top: 0; left: 0; width: 100%; height: 100%; back ...

What steps can be taken to ensure that an empty array is returned instead of a null value

I encountered a 'null pointer exception' while attempting to return an array. It seems that the problem lies in my method returning an array with elements that are null. How can I correctly return an empty array? Here is the code snippet from th ...

Trigger a modal from one sibling Angular component to another

My application utilizes an Angular6 component architecture with the following components: <app-navbar></app-navbar> <app-dashboard></app-dashboard> The Dashboard component consists of: <app-meseros> </app-meseros> < ...

Issue with implementing setTimeout on await fetch() result

I'm trying to figure out how to add a setTimeout to my request response when using await fetch. Currently, each response is being sent to a DIV in the HTML, but I want to introduce a delay of 5 seconds before each response appears. I attempted this s ...

"Type Error: Attempting to assign a value to a const variable by declaring it as let while importing a variable from another file

Within JavaScript(Node.JS), I created a config.js file as shown below to export a variable named "name": Config.js export let name = "ayush"; Then, I imported the variable "name" into the index.js file index.js import {name} from "./config.js"; name = ...