Combining two arrays using conditions in Lodash

I have two different arrays as shown below:

const firstArray = [{name: "1"}, {name: "2"}, {name: "3"}, {name: "4"}, {name: "4"}];
const secondArray = [{name: "1"}, {name: "5"}, {name: "3"}, {name: "4"}, {name: "4"}, {name: "4"}, {name: "1"}, {name: "1"}, {name: "2"}];

The desired output is:

[{name: "1"}, {name: "2"}, {name: "3"}, {name: "4"}, {name: "4"}, {name: "5"}, {name: "4"}, {name: "1"}, {name: "1"}];

The resulting array should contain all elements from the first array and any unique elements from the second array that are not already present in the first array

I attempted to use _.unionBy

_.unionBy(firstArray, secondArray, 'name')

However, this only returns an array with unique 'name' values

Is there a way to achieve this using lodash?

Answer №1

If you need to combine arrays in a specific way, consider using the unionBy method from lodash library.

let mergedArray = _.unionBy(array1 , array2, 'name');

To learn more about how unionBy works, visit

Answer №2

Suppose you don't want the object `{ name: "2" }` to be the last item in the result set, you can achieve this by calculating the grouped items and then adding the desired items accordingly.

const
    array1 = [{ name: "1" }, { name: "2" }, { name: "3" }, { name: "4" }, { name: "4" }],
    array2 = [{ name: "1" }, { name: "5" }, { name: "3" }, { name: "4" }, { name: "4"}, { name: "4" }, { name: "1" }, { name: "1" }, { name: "2" }],
    counts = {},
    result = array1.map(o => (counts[o.name] = (counts[o.name] || 0) + 1, o));

result.push(...array2.filter(o => !counts[o.name] || !counts[o.name]--));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

Changing the font color of the Y-axis in apexcharts

I am currently working on creating a candlestick chart using apexcharts, and most of it is going smoothly. However, I have encountered an issue where the color of the y-axis appears very faint and almost invisible. Despite adjusting the font size successfu ...

Is there a Scope for Switch Statements in PHP? Exploring Undefined Variables

Greetings everyone! This is my first time posting here, and I could really use some help. I'm currently facing a problem where I thought switch and If/else statements in PHP didn't have variable scope. The issue at hand is that I have a CSV file ...

Issue with Electron Remote process failing to take user-defined width and height inputs

I'm currently facing an issue with utilizing remote windows in electron. I am attempting to process user input and use that input to generate a new window with specific width and height. However, when I hit submit, nothing happens. I can't figur ...

Using jQuery to combine a conditional statement with a click event and disabling a button using the `.prop('disabled', true)` method

Looking for some assistance with this issue I've encountered. After researching on StackOverflow, I managed to find a solution to disable button clicking if the form is left empty using the $.trim(.....) code below! Success! However, adding that part ...

The Vue component mistakenly saves the image to the incorrect location when the file @change event is triggered

I've encountered an issue with my image slider component. Users have the option to add an extra image to the end of the slider, but when there are multiple instances of the same slider component on a page, it always adds the image to the first compone ...

Looking to control TextView and ImageView with a single button press, utilizing arrays and switch cases? Additionally, seeking code for implementing a previous button in an Android app?

Hey there! I am new to Android development and currently working on enhancing an activity in my app. This activity consists of a total of 10 views, including 7 text views, 2 image buttons, and 1 image view. My goal is to allow users to navigate through the ...

Ensure that clicking on an element closes any currently visible elements before opening a new element

Take a look at my code snippet below. I am working on creating multiple clickable divs that reveal different content when clicked. However, the issue I am facing is that currently, both content blocks can be displayed simultaneously. My goal is to have onl ...

What is the process for including a task in the current method?

I've been working on building a web app similar to Google Calendar. I have successfully created the necessary objects and methods, but now I need to implement a feature that allows users to add tasks. My current idea is for users to input a task which ...

Create dynamic HTML content in Angular using the ng-repeat directive

Can anyone help me figure out how to generate dynamic html content using ng-repeat with multiple ng-model instances stored in an array? I keep encountering a syntax error for {{ within ng-model. Is there a way to work around this issue? <div class="c ...

When an object is pushed into an array, it gets duplicated and also appears in a proxy when viewed in the console

Working with Firebase 9 and Vue 3 in building a chat application. The issue at hand is that when I push message objects to the messages array [], the console shows duplicates like this: Proxy {0: {…}, 1: {…}} [[Handler]]: Object [[Target]]: Array( ...

Retrieve the exact value of a key within a string

This is my unique text: let x = "Learning new things every day!"; I am utilizing the substring() method to extract a specific part of it: console.log(x.substring(9, 12)); Instead of the entire string, I only want the word 'new'. let x = "l ...

Trigger keydown and click events to dynamically update images in Internet Explorer 7

There is a next button and an input field where users can enter the page number to jump to a specific page. Each page is represented by an image, like: <img src="http://someurl.com/1_1.emf" > // first page <img src="http://someurl.com/2_1.emf" ...

Is it possible for jQuery datepicker to choose a date over a decade in the past?

Recently, I encountered an issue with jQuery-UI's datepicker where it was restricting me to select birthdays only within the last 10 years. This basically meant that users older than 10 years couldn't be accommodated :) I attempted to override t ...

What is the best way to turn each function within the module pattern into a promise?

Utilizing Angular 1.5, I have developed a factory function that returns a literal object structured as follows: return { item: null, get: function() { return item; }, create: function() { if (this.get()){ this.remove(); ...

Extract the value of a key from a particular object in a JSON array using JavaScript

I have a JSON structure that looks like this: { map: [ {"key1":"valueA1", "key2":"valueA2", "key3":"valueA3"}, {"key1":"valueB1", "key2":"valueB2", "key3":"valueB3"}, {"key1":"valueC1", "key2":"valueC2", "key3":"valueC3"}, .... an ...

What is the best way to design a multi-submit form without the need for page refreshing?

I am interested in creating a form with multiple questions where users can click "next" for each question without the page reloading. For instance Click on "Begin" On this page, there is no reload when choosing a radio option and clicking "next". How ca ...

What are the best practices for utilizing AngularJS's $sanitize service?

Recently, I stumbled upon a tutorial discussing authentication in AngularJS. The tutorial showcased an AuthenticationService that was structured similarly to this: angular.module("auth").factory("AuthenticationService", function ($http, $sanitize) { ...

Choosing links with a particular hash code

My goal is to apply an active class to links that have previously been selected with a hash. For example, if I click on: <a href="example.com/#about"> The page will display the #about section, so all links with the #about hash should now have the ...

Retrieve the <div> located outside of this particular <div> tag

I am seeking to retrieve the second div (total-price) rather than the first div. Moreover, I want to include a $ sign in the div. However, since "$" can cause an error when converting data into Integers, I am wondering if there is a way to concatenate the ...

Converting a JSON list into a JavaScript object for the purpose of creating a dynamic

Understanding how JSON's lists work when parsed as JavaScript objects is challenging for me. I am not very familiar with JavaScript, so there may be mistakes in my question and the proposed solution. Currently, I have a JSON file that needs to be conv ...