Merge the contents of three arrays into a single array

I am seeking a more streamlined method to merge these three arrays: two data arrays and a "cross" array that connects them.

3 Arrays

var drives = [
        {"drivesId": "rwd", "name": "RWD"},
        {"drivesId": "fwd", "name": "FWD"},
        {"drivesId": "awd", "name": "AWD"}
    ]

    var cars = [
        {"carId": "civic", "name": "Civic"},
        {"carId": "wrx", "name": "WRX"},
        {"carId": "mustang", "name": "Mustang"},
        {"carId": "focus", "name": "Focus"},
    ]

    var drivesXcars = [
        {"drivesXcars": "uid1", "carId": "civic", "drivesId": "fwd"},
        {"drivesXcars": "uid2", "carId": "wrx", "drivesId": "awd"},
        {"drivesXcars": "uid3", "carId": "mustang", "drivesId": "rwd"},
        {"drivesXcars": "uid4", "carId": "focus", "drivesId": "fwd"},
    ]
    

I aim to consolidate them into a single array structured like this:

var carsComplete = [
        {"drivesId": "fwd", "driveName": "FWD", "cars": [
            {"carId": "civic", "name": "Civic"},
            {"carId": "focus", "name": "Focus"}
        ]},
        {"drivesId": "rwd", "driveName": "RWD", "cars": [
            {"carId": "mustang", "name": "Mustang"}
        ]},
        {"drivesId": "awd", "driveName": "AWD", "cars": [
            {"carId": "wrx", "name": "WRX"}
        ]},
    ]
    

While I could achieve this using the standard for loop approach, I am looking for a more efficient solution as these arrays grow in size. The traditional "brute force" method doesn't suffice for me anymore.

If anyone knows of a more efficient way to accomplish this task using AngularJS and/or lodash, I would greatly appreciate your insight.

Answer №1

One way to accomplish this task is by using plain JavaScript:

const completeCars = drives.map(item => ({
  id: item.id,
  name: item.name,
  cars: drivesXcars
    .filter(car => car.drivesId === item.id)
    .map(filteredCar => cars.find(c => c.carId === filteredCar.carId))
}))

For a working example, check out JS Bin.

Answer №2

Using Underscore.js, this solution demonstrates grouping and mapping with arrays:

var groupById = _.groupBy(data, "id");
var mappedResults = array.map(function(item){
                            return {
                                "id": item.id,
                                "name": item.name,
                                "details": groupById[item.name.toLowerCase()]
                               }
                           });

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

What happens if setTimeout fails due to a page error?

My current setup involves using setTimeout to refresh the page, updating the jQuery template items. Here is a snippet of the relevant code: <script type="text/javascript"> var results = JSON.parse('@svgPath'.replace(/&quot;/g ...

What are the steps to installing and utilizing the Chart.js package on your local machine?

I thought installing chart.js on my Raspberry Pi would be a simple task, but I seem to be struggling with it. Due to the nature of my project, I need to have it installed locally rather than relying on an online version. Following the usual steps, I navig ...

VueJS throws an error indicating that the object cannot be extended

I have encountered an issue while trying to update the promo object by adding a new field called colspan. Unfortunately, I am getting this error: uncaught (in promise) TypeError: Cannot add property colspan, object is not extensible at eval (eval at ...

Validate an object to check for null or empty fields, including arrays, using Javascript

Currently, I am facing an issue with iterating through a complex array that contains objects and embedded arrays. The goal is to detect any empty or null values within the array. However, my challenge lies in accurately determining if an array is empty. De ...

Generate a new perspective by incorporating two distinct arrays

I have two arrays containing class information. The first array includes classId and className: classes = [ {classid : 1 , classname:"class1"},{classid : 2 , classname:"class2"},{classid : 3 , classname:"class3"}] The secon ...

Combine the PHP table with the Javascript table

I am facing a challenge where I have a table in PHP and another table in Javascript. My goal is to combine the elements of the PHP table with the elements of the Javascript table. I attempted to achieve this using the push method: <?php $tabPHP=[&apos ...

Modify keys in an array created dynamically using PHP

I'm working with a PHP array where each key starts with the character "@a". How can I go about removing this symbol from all keys? The challenge is that I don't know for sure what specific keys will be present, but I definitely need to get rid of ...

extensive collections with numerous empty slots

In my Java program, I currently have a line of code that initializes a multi-dimensional array like this: double[][][][][][][][][][][] array = new double[20][10][9][8][5][4][4][3][3][3][2]; Since most of these entries will remain as null, I'm wonder ...

Implementing the History API to dynamically load content into a div using Ajax

On my WordPress site, I have post content that loads into a div using AJAX when a user clicks on it. Now, I'd like to update the URL for the current post without using hashes. How can I achieve this with my JavaScript? JavaScript: jQuery(docum ...

Crashing occurs when JSON is added to a mutable array

Greetings everyone, I am a newcomer to Xcode/iOS development. I am attempting to add JSON data to a mutable array, but unfortunately, it is causing my app to crash. Here is the code I have so far: if(! [defaults objectForKey:@"Person1"]) [defaults se ...

The note-taking app's JavaScript code does not currently have the capability to store notes in local storage

const noteContainer = document.querySelector(".note-container"); const createBtn = document.querySelector(".btn"); let notes = document.querySelectorAll(".input-box"); function showNotes() { noteContainer.innerHTML = localS ...

AngularJS: Utilizing ellipsis for text overflow and optimization

As a beginner in angularJS, I might have made some mistakes... Can anyone guide me on how to properly implement this plugin: https://github.com/BeSite/jQuery.dotdotdot on my table? Currently, the performance of my edit form and table is very slow. What c ...

Creating a process to automatically generate an input field upon the selection of checkboxes

Is there a way to automatically generate a text field for each checked box in a dynamically changing checkbox list? Below is my code snippet: <div> <label> Products </label> <li ng-repeat="item in INDproducttypes"> ...

Generating a JSON object through the comparison of two other JSON objects

I need to create a new JSON object called selectedProductAttributes, which is generated by comparing the contents of a second JSON object (selectedProductAttributesNames) with a third object (allProductAttributes). Let me provide some examples to make this ...

Basic output list of text strings

Could someone please identify the error in this basic code? #include<stdio.h> #include<conio.h> void main() { int i,n; char a[100]; clrscr(); printf("\n Enter the size of the array"); scanf("%d",&n); printf("&b ...

Converting a JavaScript array to formData

Struggling with sending an array via Ajax to PHP. For more information, visit jsfiddle https://jsfiddle.net/CraigDavison/9spyn7ah/ function autoPopulate() { var cast = "John Wayne, Julia Roberts, Kevin Spacey"; cast = cast.split(', '); ...

JQuery loader & amazing animations

I have implemented the wow.js plugin along with a jQuery preload tutorial from here. Although the preloader works fine, I am facing an issue where the animation by wow.js starts before all the elements on the page are preloaded. I am looking to modify my ...

Design a progress bar that advances in increments of at least two and up to a maximum of

My task involves managing a simple list. const [progressBar, setProgressBar] = useState([ { isActive: false, name: "step1" }, { isActive: false, name: "step2" }, { isActive: false, name: "step3" }, { isActive ...

Updating the texture passed to a RawShaderMaterial uniform in Three.js after the initial rendering process

My Three.js scene uses a canvas as a uniform for a RawShaderMaterial. Once the scene is initially rendered, I modify the canvas by painting it red. Even though I set .needsUpdate = true; for the shaderMaterial, the points do not change color. If I move th ...

(discovered: [object Promise]) utilizing Material UI and DexieJS

Exploring DexieJS and Material UI for the first time has been quite a learning experience, so I may have overlooked a crucial aspect. Here is a glimpse of my code: Subscreen.tsx const [fightersArray, setFightersArray] = useState<FighterEntity[]>([]) ...