Combining arrays of objects: a step-by-step guide

We start with an array A and an array B:

   let arrA = [{
      name: 'twitter',
      active: true
    }, {
      name: 'medium',
      active: false
    },
     {
      name: 'platinum',
      active: false
    }
  ];

Array B looks like this:

let arrB = [{
      name: 'twitter',
      active: false
    }, {
      name: 'medium',
      active: false
    }
  ];

The goal is to create a new array, newArr, where the 'active' property is determined by performing an 'or' operation between the corresponding 'active' properties in arrA and arrB for matching 'name' values. Here is how newArr should look:

let newArr = [{
      name: 'twitter',
      active: true
    }, {
      name: 'medium',
      active: false
    },
    {
      name: 'platinum',
      active: false
    }
  ];

It is important to note that arrA and arrB may have different lengths.

Answer №1

This is the strategy I use. I utilize the map function.

const arrX = [{
    name: 'facebook',
    active: true
}, {
    name: 'linkedin',
    active: false
},{
    name: 'instagram',
    active: false
}];

const arrY = [{
    name: 'facebook',
    active: false
}, {
    name: 'linkedin',
    active: false
}];

const combinedItems = arrX.concat(arrY);
const mergedItemsList = new Map();
combinedItems.forEach((data) => {
    if (!mergedItemsList.get(data.name)) {
        mergedItemsList.set(data.name, data);
    } else {
        data.active = data.active || mergedItemsList.get(data.name).active;
        mergedItemsList.set(data.name, data);
    }
});
const finalMergedArray = Array.from(mergedItemsList.values());

I hope you find this information helpful!

Answer №2

  1. Initialize an empty array called newArr.
  2. Iterate through arrA and arrB, comparing object key and value, then push the result into newArr.
  3. Complete the task.

let arrA = [
      {
        name: 'twitter',
        active: true
      },
      {
        name: 'medium',
        active: false
      }
    ];
let arrB = [
      {
        name: 'twitter',
        active: false
      },
      {
        name: 'medium',
        active: false
      }
    ];
let newArr = [];
    
for (var i = 0; i < arrA.length; i++){
  newArr.push({
    name: arrA[i].name,
    active: arrA[i].active || arrB[i].active,
  });
}

console.log(newArr);

Answer №3

Check out this handy code snippet:

function mergeArrays(arr1, arr2) {
    arr1 = arr1.map(item => {
        if (arr2.some(elem => elem.name === item.name))
            item.active = item.active || arr2.filter(element => element.name == item.name)[0].active;
            return item;
        });

        return [...newArr, ...arrB.filter(elem => !arrA.some(entry => entry.name === elem.name))];
}

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

Introducing unnecessary DOM elements when displaying flash messages

When a user saves in my Rails application, it triggers an Ajax request to save the post and then runs the update.js.erb file. This file contains some jQuery code: $('body').append('<div class="message">Saved</div>'); Due t ...

Struggling to locate the element using xpath on a JavaScript enabled website in Selenium with Chrome

I have been attempting to extract data from a website that utilizes Javascript. Despite researching similar inquiries on xpath in Selenium, I have not found a solution. I initially tried using requests, but as the JavaScript doesn't load completely, I ...

Is there a way to reset useQuery cache from a different component?

I am facing an issue with my parent component attempting to invalidate the query cache of a child component: const Child = () => { const { data } = useQuery('queryKey', () => fetch('something')) return <Text>{data}& ...

What is the best way to generate hyperlinks from data in a MongoDB database?

Looking for some assistance in setting up an online discussion forum using node.js, express & mongodb. My current challenge is creating clickable links that will redirect me to the specific page of each article stored in the database. I need to figure out ...

What steps are involved in developing an Angular library wrapper for a pre-existing Javascript library?

Imagine having a vanilla Javascript library that is commonly used on websites without any frameworks. How can you create an Angular library that can be easily installed via npm to seamlessly integrate the library into an Angular application? The process o ...

Refresh client web pages with JSON data without using eval

I am currently working as a consultant on a web application that functions as a single page app. The main purpose of the app is to constantly fetch new json data in the background (approximately every minute) and then display it on the screen. Our clients ...

Parcel JS: The function tree.render is missing or not defined

Every time I attempt to execute the production build command npm run build or npx parcel build index.html, this error occurs. My project consists of simple HTML and CSS, without any React or third-party libraries. What could be causing this issue? I have t ...

Trouble with jQuery: Tackling a Basic String and Variable Issue

I'm having trouble incorporating my variable into this specific string: var liPad = 20; $(this).css({'width' : width , 'height' : height, 'padding' : "'0px' + liPad + 'px'"}); The desired outcome is ...

Using preventDefault in the compositionend event does not make any difference

var inputNode = document.getElementById('view_1'); inputNode.addEventListener('compositionend', function(e) { console.log(e.cancelable); // true e.preventDefault(); }); <div id="view_1" class="view" contenteditable="true> &l ...

How to retrieve a JSON array from a CSV file stored remotely using PHP

In one of my PHP scripts, I need to convert data from a remote CSV file into a JSON array. The URL of the remote CSV file is: www.xyz.com/dir/records.csv NAME Age ID Jhon 45 101 Bhil 42 102 Tone 41 103 I am looking for a function that can ...

Converting Text to JSON

I need assistance with converting a set of data into JSON format. Below is the current format: Text Data 192.168.0.1 192.168.0.2 192.168.0.3 192.168.0.4 192.168.0.5 192.168.0.6 192.168.0.7 192.168.0.8 192.168.0.9 I want to convert this data into JSON lik ...

Is it possible for TypeScript to automatically detect when an argument has been validated?

Currently, I am still in the process of learning Typescript and Javascript so please bear with me if I overlook something. The issue at hand is as follows: When calling this.defined(email), VSCode does not recognize that an error may occur if 'email ...

Trouble with CSS transitions not functioning while altering React state

Each time a user clicks on an accordion, the content should smoothly show or hide with a transition effect. However, the transition only seems to work when opening a closed accordion, not when closing an already open one! To get a clearer idea of this iss ...

Accessing dropdown selection in Javascript-Json: A Comprehensive Guide

My dropdown list is being populated dynamically using json. The selected option from the first dropdown determines the options in a secondary dropdown. I need to use the selection from the second dropdown to automatically fill out two more fields. For exa ...

Error: The value of "$tweetId" cannot be parsed as it is set to "undefined". Please ensure that string values are properly enclosed

I am utilizing sanity, and if you require more details, I will furnish it promptly. When I try to access http://localhost:3000/api/getComments, I encounter the following error message: ClientError: Unable to process value of "$tweetId=undefined". Kindly ...

Click event in safari failing to trigger on iPhone

Issue with click event on mobile Safari browser when using an iPhone In a React class component, the click event listener is triggered on the window when opening the menu. This functionality works correctly everywhere except for iPhone Safari. toggleMenu ...

box tick does not alter appearance

I've been struggling with this seemingly simple issue for an hour now. I have a radio button set up with two buttons: <input class="form-control icheck" id="cash_prize" name="cash_prize" type="radio" value="1" style="position: absolute; opacity: 0 ...

Refresh a div with Ajax once all data has been fully loaded

I am currently using an ajax refresh div function that reloads a specific div every 10 seconds. Occasionally, the div loads before receiving data from mysql. Is there a way to modify it so that it waits 2 seconds after reloading the div? <script type ...

Arrow function utilized in string rendered component

Hello everyone, I could use some help with the following code snippet: rowRenderer = (e) => { debugger; return e.data?.fileName ? '<a class="documentLink" onclick={() => \'' + console.log('\ ...

The ajax request functions smoothly on the OS X Paw app and cURL, but does not work properly when coded in Javascript / jQuery

Currently delving into the world of ajax requests, I've been utilizing the Paw app to troubleshoot one. Surprisingly, the request functions flawlessly within Paw itself and even the cURL code generated by Paw works like a charm. However, the JavaScrip ...