Determine if two arrays share the same keys

Looking to compare two arrays and update them with matching keys while adding 0 for non-matching keys.

For example:

let obj1 = [
{"type": "Riesenslalom","total": 2862},
{"type": "Slalom", "total": 362 },
{"type": "Super-G", "total": 579 }];

let obj2 = [
{"type": "Riesenslalom","total": 2218},
{"type": "Slalom","total": 448},
{"type": "Wall", "total": 133 }
];

Desired output:

let obj1 = [
{"type": "Riesenslalom","total": 2862},
{"type": "Slalom", "total": 362 },
{"type": "Super-G", "total": 579},
{"type": "Wall", "total": 0 }
];

let obj2 = [
{"type": "Riesenslalom","total": 2218},
{"type": "Slalom","total": 448},
{"type": "Super-G", "total": 0 }
{"type": "Wall", "total": 133 }
];

I have tried various methods but haven't been able to solve this issue. Any suggestions would be greatly appreciated!

Thanks

Answer №1

To update the arrays, pass them into a function - the first array you want to update and the second array you want to update from. Then, iterate over the objects in the first array. If the type value is not found in an object in the second array, update it with an "empty" object.

After updating, return the array sorted by type if necessary using the sort method.

Repeat the process by switching the arrays in the function arguments.

const arr1=[{type:"Riesenslalom",total:2862},{type:"Slalom",total:362},{type:"Super-G",total:579}],arr2=[{type:"Riesenslalom",total:2218},{type:"Slalom",total:448},{type:"Wall",total:133}];

function update(updateTo, updateFrom) {
  for (const { type } of updateFrom) {
    const found = updateTo.find(obj => obj.type === type);
    if (!found) updateTo.push({ type, total: 0 });
  }
  return updateTo.sort((a, b) => a.type.localeCompare(b.type));
}

console.log(update(arr1, arr2));
console.log(update(arr2, arr1));

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 it possible to combine asynchronous and synchronous functions in the same code?

I've recently started experimenting with Node.js and I'm running into issues with asynchronous functions. While I was able to create a small game, the only way I could successfully integrate asynchronous functions with synchronous functions was b ...

Is there a specific regex pattern available to identify CSS and JavaScript links within an HTML file?

Currently, I am using a straightforward gulp task to compress my CSS and JS files. The task appends a .min extension to the names of the compacted files. Now, I want to make changes in the HTML to direct to these new compressed files, like so: Replace thi ...

How to utilize Unity's JsonUtility with a class that includes arrays

In Unity, I am currently working on developing a game that utilizes Tilemaps to procedurally generate a world in a similar fashion to a 2D Minecraft setup. The game consists of two main classes: Chunk, which represents a 16x16 integer array containing tile ...

Encountering an error message that says "ERROR TypeError: Cannot read property 'createComponent' of undefined" while trying to implement dynamic components in Angular 2

I am currently facing an issue with dynamically adding components in Angular 4. I have looked at other similar questions for a solution but haven't been able to find one yet. The specific error message I am getting is: ERROR TypeError: Cannot read ...

The requested resource at http://localhost/Grafica/%7Bd.icon%7D/ was not found (Error 404)

Creating a tooltip in a weather chart, I want to display an image of the sky condition. Below is the HTML code: <div id="tooltip"> <table class="table table-condensed"> <tr><th>Time (local)</th><th data-text="d ...

What is the easiest way to include a copyright symbol in a React component?

I am trying to include the copyright symbol in a React component, but it doesn't seem to be working for me. function Footer() { return ( <footer> <p>&copy</p> </footer> ); } <p>&copy</p> ...

Testing NodeJS Database Functionality using Mocha and Asserting with should.js

Currently, I am in the process of testing my NodeJS application using mocha and should. The issue I am facing is that while the first test executes smoothly, the second one fails with an error of null. Interestingly, both tests result in a valid user being ...

methods for extracting json data from the dom with the help of vue js

Can anyone help me with accessing JSON data in the DOM using Vue.js? Here is my script tag: <script> import axios from "axios"; export default { components: {}, data() { return { responseObject: "" }; }, asy ...

Issue with nodes/JavaScript: Array objects not being properly updated

Being new to Javascript and Node.js, I attempted to code a simple program that generates an array of planes with varying index values. I started by defining a plane object with default values and tried to update the index value in a for loop. However, whe ...

Working with PHP to retrieve values from an array object

I have the following array: businesscommercialArray = { 40E: { id: 94, swift_code: "40E", status: 1 }, 43P: { id: 106, swift_code: "43P", status: 2, note: "Allowed (INSTEAD OF EXIST ...

What distinguishes node from node js?

Following the instructions on https://nodejs.org/en/download/package-manager/, I installed Node.js. Upon checking the current version using: :~/Downloads$ nodejs -v I discovered that I was running v4.2.6, which is an older version. Deciding to update, I ...

How can I clear all jQuery toggled classes that have been added across the entire webpage in an Angular project?

Upon clicking a link within an element, the following CSS is applied: <a class="vehicleinfo avai-vehicle-info-anc-tag" ng-click="vehicleInfo($event)">Vehicle Info <span class="s-icon red-down-arrow"> </span> </a> $scope.vehic ...

What is the best way to eliminate a specific value within a flatmap?

This is the flatMap: const choices = names.flatMap( (item) => item.name + " - " + item.size + "- " + item.category ); console.log(choices): https://i.stack.imgur.com/MO4b1.png If the item.category is equal to S-XL, how can ...

Text area capacity

Is there a limit to the maximum capacity of a textarea for accepting text? The HTML page functions correctly when the text is limited to around 130-140 words. However, if the text exceeds this limit, it causes the page to hang without any response. The tex ...

Why isn't setInterval set to a duration of one thousand milliseconds?

While trying to use some code from w3schools, I noticed that the setInterval in the example is set to 5 instead of 5000. Shouldn't it be in milliseconds? If not, how can I speed up this animation? When I try reducing it to decimals like 0.01, the anim ...

Error message: Next.js - Unable to access properties of an undefined object (user)

I am currently utilizing Next.js and Next-auth in my current project. Within this project, I am working on creating a Sidebar component that will display a list of items specific to each user. To achieve this, I am using the useSession hook to retrieve t ...

AngularJS - Shared service object mistakenly removed in error

When I call the removeQuestion() function for the second time, 2 questions are being deleted instead of one. Any suggestions on what might be causing this issue? Let me know if you require additional code snippets. controller.js crtPromoCtrl.controller(& ...

The functionality of Ajax is limited when it comes to handling multiple div elements at the same

Seemingly silly question ahead, but I've been grappling with it for days to no avail. If anyone can help me solve this, please state your price and provide your PayPal details – the money is yours :). What I'm trying to achieve is to add a "Add ...

Is there a way to update the Angular component tag after it has been rendered?

Imagine we have a component in Angular with the selector "grid". @Component({ selector: 'grid', template: '<div>This is a grid.</div>', styleUrls: ['./grid.component.scss'] }) Now, when we include this gri ...

Troubleshooting Problem: Difficulty accessing Controller in AngularJS Module

I am facing difficulties with communication between my application and a module that I have developed. Below is the AngularJS module that I created. (function (document, window) { 'use strict'; var piCart = angular.module('piCart& ...