What is the best way to obtain a distinct collection from two arrays that eliminates the second appearance of an element based on a key's value, rather than the first as in the Lodash uniqueBy function?

Let's say I have two arrays...

const arr1 = [ { id: 1: newBid: true } ];

const arr2 = [ { id: 1, newBid: false }, { id: 2, newBid: false } ];

My goal is to end up with an array that looks like this

[ { id: 1, newBid: false }, { id: 2, newBid: false } ]

However, I specifically want the { id: 1, newBid: true } from arr1 and not arr2

I tried using Lodash uniqBy(arr1, arr2, ['id']), but it removes the first occurrence, not the second

Answer №1

For merging arrays in JavaScript, consider using the lodash library's mergeWith function.

const arr1 = [{
  id: 1,
  newBid: true
}];

const arr2 = [{
  id: 1,
  newBid: false
}, {
  id: 2,
  newBid: false
}];

function customizer(firstValue, secondValue) {
  if(firstValue) 
      return firstValue;
  else
      return secondValue;
}

console.log(_.mergeWith(arr1, arr2, customizer));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.js"></script>

Answer №2

When faced with these types of problems, I often opt to utilize an object as a map for convenience.

const arr1 = [ { id: 1, newBid: true } ];

const arr2 = [ { id: 1, newBid: false }, { id: 2, newBid: false } ];

const map = {};

function populateMap(array) {
    for(let i = 0; i < array.length; i++) {
        const item = array[i];
        map[item.id] = item;
    }
}

populateMap(arr1);
populateMap(arr2);

console.log(Object.values(map))

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

Windows location does not change after an XMLHttpRequest is made

Here is my code that uses XMLHttpRequest: function SignUp() { signUpConnection = new XMLHttpRequest(); signUpConnection.onreadystatechange = processRegistration; signUpConnection.open('GET', 'index.php?registrarse=&username= ...

Number each element in sequence

Looking to give sequential numbering to elements by iterating through them. For instance, if there are 6 input elements, the goal is to update their names correspondingly like "name=input1", "name=input2", and so on. This involves using a for loop to reas ...

Check for equality with an array of objects when reacting to changes

I have an input field and an array of objects. I want the object with a property named "airplaneCompany" to be displayed as I type. Each character should be checked, and if the object's "airplaneCompany" property starts with 'a', it should b ...

What is the process for embedding a NextJS app within a different website?

I'm searching for alternative methods to embed a React/NextJS application within another application. Currently, my solution involves using an iframe and specifying the source as the execution of the React/Nextjs application. I've explored diff ...

Next.js encountered an invalid src prop

Error: The src prop is invalid () on next/image, the hostname "scontent-atl3-2.xx.fbcd.net" has not been configured under images in your next.config.js For more information, visit: https://nextjs.org/docs/messages/next-image-unconfigured-host ...

Developing interactive checkboxes for individual rows through React.js

Within a form, I have rows containing two inputs each. Upon clicking "add", a new row is created. For the second row onwards, by clicking "add" a checkbox labeled 1 should be added to indicate dependency on the previous row. In addition, for the third row, ...

Error encountered in vue.js due to a ReferenceError when the resize event is used

I'm having trouble obtaining the window height when resizing, and I keep encountering the error ReferenceError: calcOfSliderHeight is not defined. Can someone explain what's happening? Here is my code: let example = new Vue({ el: '#exam ...

Create a custom validation function that accepts additional parameters

At the moment, I have implemented the following code but I haven't utilized the extra data yet. create-room.component.ts import { Component, Inject, OnInit } from '@angular/core'; import { AbstractControl, FormBuilder, FormControl, FormGroup ...

Avoiding jQuery selector

What is the reason for the selector working in the first example but failing in the second one? Check out jsfiddle. <div id="hello[1][2]_world">&nbsp;</div> <textarea id="console"></textarea> <script> $(document).re ...

A mobile phone screen cannot be fully filled by an image

I'm working on a way for an image to cover the entire screen of a mobile phone. However, when I preview it on an iPhone through a laptop, the image only covers a small portion of the iPhone's screen rather than filling it completely. Below is the ...

Setting up Highcharts version 7 heatmaps with npm in an Angular 6 environment

I am currently having an issue with initializing the heatmap lib in Highcharts 7.0.1 within my Angular 6 app via npm. Despite successfully running basic charts like line, spline, bar, etc., when following the documentation for the heatmap initialization, I ...

There was an issue with the v-on handler: "An error occurred because it was unable to read properties of an undefined value (specifically 'input')."

Can anyone help me? When I click the icon inside the avatar, I want to select a file. But I'm getting an error: Error in v-on handler: "TypeError: Cannot read properties of undefined (reading 'input'). Could anyone help me? <v-row v-for=" ...

Unable to get OverlayView() from Google Maps API to function within an AngularJS directive

My directive "map" is encountering a namespace issue. The mapInit() function is working perfectly, but there seems to be an error with my OverlayView() object that I can't seem to resolve. This is the initial step outlined in the Google documentation ...

Update the styling of each div element within a designated list

Looking for a way to assist my colorblind friend, I am attempting to write a script. This is the layout of the page he is on: <div class="message-pane-wrapper candy-has-subject"> <ul class="message-pane"> <li><div style=" ...

Using Vue.js to apply different CSS classes based on multiple conditions

Is there a way to highlight rows in a table based on specific conditions? For example, when the fine is greater than zero (fine > 0) or the due date is later than today. The current code works well for highlighting rows where issue.fine is greater than ...

Automatically redirect to a different page upon clicking the jquery popup button

I integrated a jQuery popup feature on my website to display messages. Now, I am looking to implement a redirect to another page when the user clicks a button within the jQuery popup. However, I am unsure of how to achieve this. <script type="text/ja ...

What is preventing Bootstrap properties from being applied to HTML elements appended to the DOM through JavaScript?

Currently, I am immersed in a project that utilizes Bootstrap to generate various nested components styled in accordance with Bootstrap's class system. I triumphantly crafted a card component using Bootstrap, but encountered a challenge when attemptin ...

Invoke a codebehind function using jQuery

I am encountering an issue while trying to complete a simple task. I am attempting to pass values to a code behind method, perform some calculations, and then return the result. Initially, I started with a test method but have not been successful in making ...

Converting XML schema to JSON format using Node.js

I am attempting to loop through or access keys of a JSON object that was created from an XML object in node.js. Here is my current code: var fs = require('fs'); var parser = require('xml2json'); var xsd = require('libxml-xsd&apos ...

Is there a way to sort the output of an observable in various different methods?

One interesting feature I have implemented is a TableData type observable that provides me with a collection of table rows and columns. The user has the option to select a set of columns from a dropdown menu (which corresponds to the rows) to be sorted in ...