Combining Two Arrays Based on Unique Identifier

Seeking guidance on enhancing this method to eliminate the need for a workaround.

I have two separate Object Arrays containing JSON data. The first array consists of all dates within a specific range, while the second array is derived from a SQL query, potentially lacking some months.

The desired output should be a sorted list of all months with a matterCount value assigned. However, when I utilize the function below, I encounter an issue where the matterCount is missing for months not present in the list.

I believe that there might be a small code snippet missing from the function causing this problem, but I am uncertain about the exact solution which led me here for help.

Although I have a workaround available on JSFiddle, I prefer cleaner and clearer code.

let x = [{labelDate: "Jun 2013"},
{labelDate: "Jul 2013"},
{labelDate: "Aug 2013"},
{labelDate: "Sep 2013"},
{labelDate: "Oct 2013"},
{labelDate: "Nov 2013"},
{labelDate: "Dec 2013"},
{labelDate: "Jan 2014"},
{labelDate: "Feb 2014"},
{labelDate: "Mar 2014"},
{labelDate: "Apr 2014"},
{labelDate: "May 2014"}];


let y = [{labelDate: "Jun 2013", matterCount: "1"},
{labelDate: "Jul 2013", matterCount: "2"},
{labelDate: "Aug 2013", matterCount: "2"},
{labelDate: "Sep 2013", matterCount: "10"},
{labelDate: "Oct 2013", matterCount: "1"},
{labelDate: "Nov 2013", matterCount: "1"},
{labelDate: "Feb 2014", matterCount: "1"},
{labelDate: "Apr 2014", matterCount: "17"},
{labelDate: "May 2014", matterCount: "21"}];

const merge = (x, y) =>
            x.map(xItem => ({
              ...y.find(yItem => yItem.labelDate === xItem.labelDate && Item),
              ...xItem
            }));

Actual outcome 
merge = [{labelDate: "Jun 2013", matterCount: "1"},
{labelDate: "Jul 2013", matterCount: "2"},
{labelDate: "Aug 2013", matterCount: "2"},
{labelDate: "Sep 2013", matterCount: "10"},
{labelDate: "Oct 2013", matterCount: "1"},
{labelDate: "Nov 2013", matterCount: "1"},
{labelDate: "Dec 2013"},
{labelDate: "Jan 2014"},
{labelDate: "Feb 2014", matterCount: "1"},
{labelDate: "Mar 2014"},
{labelDate: "Apr 2014", matterCount: "17"},
{labelDate: "May 2014", matterCount: "21"}];

desired outcome 
merge  = [{labelDate: "Jun 2013", matterCount: "1"},
{labelDate: "Jul 2013", matterCount: "2"},
{labelDate: "Aug 2013", matterCount: "2"},
{labelDate: "Sep 2013", matterCount: "10"},
{labelDate: "Oct 2013", matterCount: "1"},
{labelDate: "Nov 2013", matterCount: "1"},
{labelDate: "Dec 2013", matterCount: "0"},
{labelDate: "Jan 2014", matterCount: "0"},
{labelDate: "Feb 2014", matterCount: "1"},
{labelDate: "Mar 2014", matterCount: "0"},
{labelDate: "Apr 2014", matterCount: "17"},
{labelDate: "May 2014", matterCount: "21"}];

https://jsfiddle.net/cp39aoyf/2/

Answer №1

Have you considered using a default value with the logical OR operator:

const merge = (x, y) =>
        x.map(xItem => ({
          ...y.find(yItem => yItem.labelDate === xItem.labelDate && yItem) || {...xItem, matterCount: "0"}
        }));

Check out the demo on JSFiddle.

Alternatively, you could add the default value and allow it to be overridden by yItem:

const merge = (x, y) =>
    x.map(xItem => ({
      ...xItem,
      ...{matterCount: "0"},
      ...y.find(yItem => yItem.labelDate === xItem.labelDate && yItem)
    }));

Here's a Fiddle showcasing this approach.

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

retrieving the parent of the a tag from a jquery form

When using the jQuery code below: $('#trade-offer form').on("submit", function(event) { event.preventDefault(); var stock = $(this).closest('.allloopedover'); console.log(stock); return; $.ajax({ url: ajaxur ...

Is there a way to search through nested, nested arrays of JSON data using JSON_TABLE in SQL?

Hey there! I'm new to JSON and I'm trying to query a complex JSON data structure using JSON_TABLE. Here is the data and the query I've come up with. The problem I'm facing is that the phone number is nested within an array and I'm ...

Warning: Unchecked method call; <t>sort(java.util.list<T>)

Currently, I am in the process of writing code for an appointment book which involves working with several different classes. However, I seem to be encountering an error that is giving me some trouble. The error message indicates that there is an unchecked ...

Tips for creating a vertical drawer using jQuery and CSS

Hello, I am currently working on developing a drawer component using Ember.js. If you want to view the progress so far, feel free to check out this jsbin http://jsbin.com/wulija/8/edit My goal is to have the drawer look like the following initially: +--- ...

One way to filter using a single array

Currently testing some angularJS with this particular example http://www.w3schools.com/angular/tryit.asp?filename=try_ng_filters_filter <ul> <li ng-repeat="x in names | filter : 'i'"> {{ x }} </li> </ul> Is ther ...

What could be the reason for the inability to generate the response using response.writeHead and response.write functions?

I recently started learning about node.js and I'm facing an issue with the code inside the if and else loop for the '/socket.html' case. Despite my efforts, I always get a 200 status code and a blank response when accessing the URL localhost ...

Form submission in Firefox experiences a delay due to the 'Storage' function

Below is a simple submit button that submits a form: <!DOCTYPE html> <html> <head> </head> <body> <form action="action" method="POST> <button type="submit">Submit</button> </form> ...

Navigating with the keys is disabled until an item is chosen

Currently working on a Shopify website for a client and encountered an issue where the keys don't scroll down upon page load unless a specific element is clicked or tab is used. I am not sure what caused this unexpected behavior, it may have occurred ...

How can I shrink a PHP array into a significantly smaller JSON file?

I have a PHP array coming from a webservice (soap xml) that I want to filter and convert to JSON (refer to the example below). Check out the sample of the array received from the webservice: (*** indicates the data needed in the final JSON) {"Id":445946 ...

What is the proper way to send a list of lists from Ajax to Flask?

Attempting to send a list of list datatype data from a template using AJAX. Here is the code: Template (JS) var mydata = [['tom', 18, 'new york'], ['jack', 16, 'london']]; var data = new FormData(); mydata.forEach( ...

What is the process for displaying the save file dialog in Safari?

I'm struggling with generating a PDF and saving it as a file in Safari using an Angular app and DocRaptor. I've tried various methods from Stack Overflow, but none seem to trigger the save file dialog. Instead, they either open the file in the cu ...

The issue of AFrame content failing to display on Google Chrome when used with hyperHTML

There seems to be an issue with A-Frame content not rendering on Chrome, despite working fine on FireFox and Safari. According to the demonstration on CodePen here, const { hyper, wire } = hyperHTML; class Box extends hyper.Component { render() { retu ...

Using ReactJS and Electron to run a function that is passed as a string variable

Imagine having a variable called foo='someFunc' and being able to call someFunc() afterwards. If you're interested, there is an article discussing how to achieve this in pure javascript here. Unfortunately, I'm facing challenges achie ...

Updating Angular view based on service parameter change

In-depth Inquiry I have a specific setup with a header view and a main view in my Angular application. The goal is to include a "back" button in the header that should only be visible based on the current page I'm viewing. Actions Taken In my app ...

Set the background color of the Material UI Drawer component

Need some advice on changing the background color of Material UI's Drawer. I've attempted the following approach, but it's not producing the desired result. <Drawer style={customStyle} open={this.state.menuOpened} docked={false} ...

HTML string decoded incorrectly in CodeIgniter due to encoding error

When I send data that includes an HTML string along with other information from JavaScript to the PHP (Codeigniter) server using AJAX and JSON, I notice that the style information within the HTML string is missing once it reaches the server. Everything els ...

Creating dynamic visual elements on a webpage using HTML: Video

As I continue to learn HTML, CSS, and JavaScript to create a basic website for educational purposes, I have successfully embedded a video stored in my drive using the video element on an HTML page. However, I now aim to also display the video's title, ...

Steer clear of manually inputting URLs in your React components

As I embark on my journey with Gatsby, I am noticing a recurring pattern in my code. A prime example is when creating links, where I often find myself doing something like this: import {kebabCase} from "lodash"; // ... <Link to={`tags/${kebabCase( ...

The array is producing accurate results, however it is displaying as undefined in the HTML output

I have encountered a problem while working on my project. I am utilizing an API to fetch an array of platforms where a video game is available. Although the array is returning the correct data, I am facing difficulty in displaying these values in my HTML a ...

Is there a way for TypeScript to recognize that the potential data types in a union type align with the valid prototypes for a function? Any solutions available?

There seems to be an issue with this (playground link) code snippet: type ReplaceAll2ndArgType = string | ((substring: string, ...args: unknown[]) => string) export async function renderHTMLTemplate( args: Record<string, ReplaceAll2ndArgType> ...