In JavaScript, you can use either Underscore or Lodash to compare two arrays of objects and create a new array containing the

In need of assistance, please. I have two arrays apple = [1,5,10,15,20], bottle = [1,5,10,15,20,25]. Using either lodash or any JavaScript function, I am attempting to create a new array called 'c' that contains only unique elements such as c= [25]. Essentially, I want to compare the 'apple' array with the 'bottle' array and then display all the elements that are unique.

Answer №1

One approach is to utilize Array#filter in conjunction with a Set representing the opposite array.

This method employs a complement function, returning true if element a is not present in set b.

In order to achieve a symmetric difference, filtering with callback functions must be applied on both ends.

function getComplement(collection) {
    // Initialize and retain a set generated from the provided collection
    var set = new Set(collection);
    // Define an iterator callback for .filter()
    return function (item) {
        return !set.has(item);
    };
}
var apple = [1,5,10,15,20], 
    bottle = [1,5,10,15,20,25],
    unique = [
        ...apple.filter(getComplement(bottle)),
        ...bottle.filter(getComplement(apple))
    ];

console.log(unique);

Answer №2

You have the ability to craft your own function using reduce() and filter() to achieve this task.

var apple = [1,5,10,15,20], bottle = [1,5,10,15,20,25] 

function findUniqueElements(arr1, arr2) {
  var mergedArray = arr1.concat(arr2);
  var countObj = mergedArray.reduce(function(result, element) {
    result[element] = (result[element] || 0) + 1;
    return result;
  }, {});
  
  return Object.keys(countObj).filter(function(element) {
    return countObj[element] == 1;
  });
}

console.log(findUniqueElements(apple, bottle))

A more concise version of the same code using ES6 arrow functions.

var apple = [1,5,10,15,20], bottle = [1,5,10,15,20,25] 

function findUniqueElements(arr1, arr2) {
  var countObj = arr1.concat(arr2).reduce((r, e) => (r[e] = (r[e] || 0) + 1, r), {});
  return Object.keys(countObj).filter(e => countObj[e] == 1);
}

console.log(findUniqueElements(apple, bottle))

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

Encountered an error: data.map is not functioning as expected in the React component

Hi there, I've encountered a small issue with my modal component. The error message I'm getting is: Uncaught TypeError: meatState.map is not a function. Any suggestions on what may be causing this problem? Your assistance would be greatly appreci ...

Issue with ng-repeat causing input inside repeater to become blurry in AngularJS

I'm facing a similar issue as the one discussed here: https://groups.google.com/forum/#!msg/angular/eB19TlFHFVE/Rlh--XImXeYJ Here's the fiddle link: http://jsfiddle.net/KGu9n/25/ The problem I'm encountering is that my save function is tri ...

Ways to resolve axios promise

My current task involves working on a GET request from an API. Upon receiving the response shown in the image, I noticed that the data presented in the promise is accurate. My goal is to display the letters and their corresponding promise data within the H ...

Switch out the keyup event action for a click event action

http://jsfiddle.net/2q8Gn/23/ I am looking to modify the provided fiddle so that instead of having computedPageLinks update with each key press in the search input, it updates only when a button is clicked and does not change when the search input loses f ...

What is the best way to select a specific value from JSON (Webhook) Data?

I am looking for a way to extract and store a specific value from a JSON data into a variable. Specifically, I want to save the value of Name (John) in a variable like this: var name = "". I attempted using var name = data.Name but it is not wor ...

Using JavaScript to organize and categorize data within an array

I am working with a multidimensional array and need to filter it based on the value at a specific index position. Here is what the array looks like: arr = [ [1 , 101 , 'New post ', 0], [2, 101 , 'New Post' , 1], ...

Methods for transferring checkbox values from JavaScript/view to controller in MVC

Currently, I am developing a form that allows users to select up to 11 football players from a list using checkboxes. The players are categorized and named by their playing positions. @if(item.PlayerPosition.FantasyFootball_PlayerToSeason.Select(x => x ...

Creating dynamic input fields in JavaScript by using class-based methods

I have a requirement to dynamically duplicate a couple of fields whenever the user clicks on the Add button and then capture the data from these fields. While searching online, I came across various tutorials like Tutorial which demonstrate how to create n ...

Converting a string to a JSON array with Jackson in RESTful APIs

As I delve into the world of JSON and REST, I find myself testing a REST API that returns strings in the following format: [{ "Supervisor_UniqueName": "adavis", "Active": "true", "DefaultCurrency_UniqueName": "USD", "arches_type": "x-zensa ...

Issues Arising from Abstraction of Function to Service Layer in Angular Application

I have a filter function that takes in user filter selections and returns data accordingly. Currently, I am using this function in multiple components to avoid repetition (DRY). To streamline the process, I decided to refactor it into a service layer. Howe ...

Refresh the Data Displayed Based on the Information Received from the API

As someone who is relatively new to React, I have been making progress with my small app that utilizes React on the frontend and a .NET Core API on the server-side to provide data. However, I have encountered a problem that I've been grappling with fo ...

A guide to displaying the combined values of identical items across multiple dates using react.js

Here is an example of an array I have: array = [ { "id": 1, "date": { "id": 1, "name": "202001" }, "item": { "id": 1, "name": "I1 ...

Accessing the ng-model value from an input type number within an AngularJS ng-repeat directive allows for

I am facing an issue where I am only able to console.log the value '10' from the table, even though I want to log the value chosen in the input field. Here is a link to my Plunker for reference: http://plnkr.co/edit/g1t4pludTTIAJYKTToCK?p=preview ...

JavaScript - convert the values of an array within a JSON object into separate strings

I am receiving a JSON object from an API, and my next step involves some string analysis of each key value. This process works perfectly for 90% of the objects I receive because the key values are strings. { ID: '0012784', utm_source: 'webs ...

Expanded MUI collapsible table squeezed into a single cell

I'm experimenting with using the MUI table along with Collapse to expand and collapse rows. However, I've noticed that when utilizing collapse, the expanded rows get squished into one cell. How can I adjust the alignment of the cells within the p ...

Transforming the timezone of a date from the Backend to the timezone selected by the user in the User

I have an API that provides dates in the format: 12/23/2023 at 03:31 a.m. CST My goal is to convert this to a date with the user-selected timezone in the following format: 12/23/2023 at 7:31 p.m. The timezone part is not required for display in the UI. c ...

Trouble with Gulp and Browserify

Recently, I started diving into the world of gulp and browserify. Here's the setup in my gulpfile.js: gulp.task('default', function (done) { var b = browserify({ entries: ['app/app.js'], }); var browserifie ...

`Is it possible to place div elements on the left and right sides of another div element?`

Is there a way to format two div elements so that they are aligned to the left and right of another div element, similar to the example below? <div id="container"> <div id="left">Left.</div> <div id="box">This is a box.&l ...

Concealing a child component when hovering over its parent element with styled-components

I have a react component structured like this - const MyComponent = () => ( <ContainerSection> <DeleteButtonContainer> <Button theme="plain" autoWidth onClick={() = ...

Enclose the string stored in the variable with double quotation marks

I am retrieving a variable called audioUrl from the database which is stored as a string url. The issue I am facing is that the url does not have double quotes around it, so I need to add them manually. Below is my code snippet: var audioUrl; // The ur ...