Matching two arrays and performing an operation on them

Is there a way to search for a specific value in an array and if it exists, then add another value into a different array?

I have two large arrays: one containing people and the other containing blogs. I want to accomplish this using JavaScript. Here is a simplified example of my arrays:

arr2 = [
    {
        "post_title": "In-House Counsel’s Role in Optimizing Intellectual Property",
        "post_date": "@1667970000",
        "custom": {
            "author": [
                {
                    "type": "attorney",
                    "identifier": "Deborah Stehr"
                }
            ]
        }
    },
    // Additional objects from arr2 ...
]

arr1 = [
    {
        "post_title": "Deborah Stehr",
        "custom": {
            "title": "Senior Counsel"
        }
    },
    // Additional objects from arr1 ...
]

I aim for the arr1 array to output the following after manipulation:

[
    {
        "post_title": "Deborah Stehr",
        "custom": {
            "title": "Senior Counsel",
            "related_posts": [
                {
                    "type": "blog",
                    "identifier": "In-House Counsel’s Role in Optimizing Intellectual Property"
                },
                // Additional related posts for Deborah Stehr ...
            ]
        }
    },
    // Additional transformed objects from arr1 ...
]

This is the approach I took but it only captures the first object from arr2:

for(var i=0; i < arr2.length; i++){
    if(arr2[i].custom.author[0].identifier == 'Deborah Stehr'){
        for(var t=0; t < arr1.length; t++){
            if(arr1[t].post_title == 'Deborah Stehr'){
                arr1[t].custom.related_posts = [];
                arr1[t].custom.related_posts.push({
                    "type": "blog",
                    "identifier": arr2[i].post_title
                })
            }
        }
    }
}
// Addition of similar loops for other authors...

The current implementation works but only handles the first object from arr2. How can I loop through both arrays to achieve the desired outcome?

Answer №1

Your initial iteration is only returning the first related post because of the way you have structured the code.

arr1[t].custom.related_posts = [];

To ensure all related posts are added, move the initialization of the related posts array outside the loop that searches for matches.

A single loop through arr1, followed by matching elements in arr2, will suffice instead of multiple loops for each post title.

Simplify your code using forEach() for better readability and eliminating complex array indexing.

const arr1 = [{
    "post_title": "Deborah Stehr",
    "custom": {
      "title": "Senior Counsel"
    }
  },
  {
    "post_title": "Lori S. Ross",
    "custom": {
      "title": "Attorney, Member of the Firm"
    }
  },
  {
    "post_title": "Brian Heller",
    "custom": {
      "title": "Attorney, Member of the Firm"
    }
  }
];

const arr2 = [{
    "post_title": "In-House Counsel’s Role in Optimizing Intellectual Property",
    "post_date": "@1667970000",
    "custom": {
      "author": [{
        "type": "attorney",
        "identifier": "Deborah Stehr"
      }]
    }
  },
  {
    "post_title": "Understanding the Privacy Right to Be Forgotten",
    "post_date": "@1667797200",
    "custom": {
      "author": [{
        "type": "attorney",
        "identifier": "Lori S. Ross"
      }]
    }
  },
  {
    "post_title": "3 Creative Ideas for Writing a More Compelling Collection Letter",
    "post_date": "@1667361600",
    "custom": {
      "author": [{
        "type": "attorney",
        "identifier": "Brian Heller"
      }]
    }
  },
  {
    "post_title": "FTC Shines a Light on Digital Dark Patterns",
    "post_date": "@1666670400",
    "custom": {
      "author": [{
        "type": "attorney",
        "identifier": "Lori S. Ross"
      }]
    }
  },
  {
    "post_title": "New California Law Requires Physicians to Notify Patients about Open Payments Database",
    "post_date": "@1666584000",
    "custom": {
      "author": [{
        "type": "attorney",
        "identifier": "Deborah Stehrn"
      }]
    }
  },
  {
    "post_title": "Exclusive Use Provisions in Commercial Leases",
    "post_date": "@1663819200",
    "custom": {
      "author": [{
        "type": "attorney",
        "identifier": "Brian Heller"
      }]
    }
  }
];

arr1.forEach(post => {
  let title = post.post_title;
  post.custom.related_posts = [];
  arr2.forEach(post2 => {
    if (post2.custom.author[0].identifier == title) {
      post.custom.related_posts.push({
        type: "blog",
        identifier: post2.post_title
      });
    }
  });
});

console.log(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

Make sure to include the onBlur and sx props when passing them through the slotsProp of the MUI DatePicker

This DatePicker component is using MUI DatePicker v6. /* eslint-disable no-unused-vars */ // @ts-nocheck import * as React from 'react'; import { Controller } from 'react-hook-form'; import TextField from '@mui/material/TextField&a ...

Ways to display a different div when clicking on a div?

Good afternoon, I've noticed that this question has been asked numerous times before, but none of the solutions provided seem to work for my specific issue. My problem involves a div with the class .title3. I want another div with the class .Content ...

Is it possible to configure npm install to install "bin" executables directly into the local node_modules directory (rather than the .bin directory)?

In my Node project, I am able to package it into a tarball using npm pack, and then install it in another directory for testing purposes. This allows the files specified in the "bin" section of my package.json file to be symlinked correctly into the node_m ...

What is the best method for showing jQuery/Javascript functions in the HTML <pre> element as a string

I am curious about converting jQuery or JavaScript functions to a string and displaying them in an element like <pre> HTML : <pre></pre> jQuery : function test() { alert('test'); } $('pre').html(test()); // &l ...

Generating a dropdown selection list using data from a JSON file

package com.example.root.myapplication; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Button; import android.wi ...

Resolving issues with setting up d3.js in the 'Creating a Custom Map' guide

Starting Mike Bostock's tutorial on creating a map, but facing some installation issues at the beginning. I am using Windows 8.1 for this. This is the specific part that's causing trouble: "To get started, you'll need the reference implemen ...

Is it feasible to lower AWS data transfer expenses by transitioning from HTTP APIs to gRPC services?

My web service handles a large volume of traffic, sometimes reaching millions per minute. It is hosted on AWS EC2 behind an ELB and utilizes HTTP APIs, resulting in a significant portion of my AWS bill going towards Data Transfer fees. The Data Transfer Ou ...

The bar graph dataset is not correctly configured when utilizing ng2 charts and ng5-slider within an Angular framework

Currently, I am working with a range slider and bar graph. My goal is to dynamically change the color of the bar graph using the range slider. While I have managed to successfully alter the color of the bars, I am facing an issue where the data displayed ...

When attempting to retrieve the HTTP status, an ObjectDisposedException is returned

I'm having trouble retrieving the status code from an http response, like so: try { HttpWebRequest request = WebRequest.Create(requestURI) as HttpWebRequest; string text using (HttpWebResponse response = request.GetResponse() as HttpWebR ...

Issue with JQuery on("submit") event not triggered upon first click

I'm currently using JQuery to check the size of an input field after submitting a form: <!DOCTYPE html> <html lang="en> <head> <title>Page 1</title> <meta charset="utf-8"/> <script src="https://ajax.google ...

What is the term for the operation of "pairing each with each"?

I am working with a matrix represented in PHP as an array: array( array('x', 'y'), // x | y array('z', 'w') // z | w ) Now, I have a second matrix also represented in a similar way (without inner a ...

Neither the context nor props contain the element 'store' that you are searching for

Just stepping into the world of React can be overwhelming, but I'm determined to get my page to render properly: import React, { Component } from "react"; import { connect } from "react-redux"; import Header from '../components/Header'; imp ...

Changing a string to uppercase and lowercase

I am currently working on a software that takes a string, divides it, capitalizes the first letter of the first string, and capitalizes all letters in the second string. Below is the code snippet: var fullName = "ThEoDORe RoOseVElT"; function nameEditor( ...

Passing a portion of a StringArray to the next Activity by clicking on a ListItem:

In Activity1, I have a ListView with 10 items. When I click on an item, I want to pass a portion of a StringArray to my next Activity and bind it to a GridView using an ArrayAdapter. First Issue: I'm unsure how to pass data to the next Activity based ...

Using Nested ng-repeat for Values and Keys in Angular

Struggling with implementing nested ng-repeats in my code. I have a JSON object with multiple layers and attempting to iterate through them to display the data. Here is the structure of the JSON: { "status": "success", "data": { "Mat": { "tota ...

display object issue with object display

I'm encountering a strange issue with my constructor objects in JS - when I try to view them, all I see is [object Object]. Can anyone help me figure out why this is happening? Check out the code snippet on MyCodeFiddle. ...

What could be causing my external JavaScript file to not function properly upon loading my HTML file?

I have organized my code by separating the HTML and JavaScript portions. The JavaScript code is now in its own separate file and I use 'script' tags to reference it in the HTML file. Within the JavaScript code, I have two functions - one creates ...

How can I return both a JSON and binary file in an API using REST practices?

As part of my task, I need to create a REST endpoint that accepts start and end dates along with other arguments. This endpoint will perform computations and generate a forecast based on the server state at the time of invocation as well as the input data ...

Issues with React useState persisting new values between useEffect intervalsHere is a rephrased

I am attempting to store jokes and log a new value every time the interval runs (triggered by a get call) after 5 seconds. However, for some reason, the value is not rendering anything after each interval. I'm not certain if the jokes are actually bei ...

I'm encountering a strange issue where Node JS is mistakenly claiming that the method doesn't exist, even though

Ah, it seems I've encountered an error in my test project. The issue lies with Node JS not being able to locate the getStr function within the Another object. Allow me to share the code with you: test.js var Another = require('./another.js&apo ...