What is the reason behind the one-way functionality of underscore's difference method?

If I asked you, "What separates these two arrays: ['a'] and ['a', 'b']?" your answer would be 'b', correct?

I'm curious why underscore doesn't automatically provide bidirectional diff functionality. How can we use other methods to achieve this result?

var x = ['js-email'],
    y = ['js-email', 'form-group'],
    z = _.difference(x, y), // outcome: []
    w = _.difference(y, x); // outcome: ["form-group"]

Check out this example on JSFiddle.

To clarify, I want the difference between the arrays to always be ['form-group'], regardless of their order.

Answer №1

To find the unique elements between two sets, you can simply combine the differences in both directions.

function getUniqueElements(firstSet, secondSet) {
    return _.union(_.difference(firstSet, secondSet), _.difference(secondSet, firstSet));
}

console.assert(getUniqueElements(["a", "b"], ["a", "c"]).toString() == "b,c");
var setA = ["js-email"], setB = ["js-email", "form-group"];
console.assert(getUniqueElements(setA, setB).toString() == "form-group");

If you wish to incorporate this function into the _ library itself for easy access throughout your project, you can use the _.mixin method like this:

_.mixin({
    getUniqueElements: function(firstSet, secondSet) {
        return _.union(_.difference(firstSet, secondSet), _.difference(secondSet, firstSet));
    }
});

Then you can call the function like this:

console.assert(_.getUniqueElements(["a", "b"], ["a", "c"]).toString() == "b,c");
var setA = ["js-email"],
    setB = ["js-email", "form-group"];
console.assert(_.getUniqueElements(setA, setB).toString() == "form-group");

Answer №2

.difference works similarly to PHP's array_diff and similar functions by returning items that exist in the first array but not in any of the other arrays passed to it.

It's important to note that "the things in a that aren't in b" is not the same as "the things in b that aren't in a", which is why this behavior is intentional.

To achieve a bidirectional difference, you will need to run the function in both directions and then remove duplicates from the final result.

Answer №3

_.differencecan take in multiple arrays as input:

It works like excluding elements present in other arrays and only keeping unique values from the original array

This function is intended for one-way operations.

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

discovering the category for the .click function

After retrieving a list of book objects from a JSON object, I am in the process of displaying them on an HTML page by creating buttons with titles. The goal is to alert the URL of the book when a button is clicked. However, I am facing an issue with access ...

How can we optimize the sluggish performance of the pattern match loop?

After writing a bash script to analyze the flow of an FTP connection by searching for a username or IP address, I found that the performance was unsatisfactory. Following suggestions from the experts exchange community, I decided to try rewriting the scrip ...

How can you place text on top of an image using JQuery and CSS?

I've been working on overlaying text over an image using Jquery and css. The overlay text is displaying nicely on the image, but I'm struggling to change the font and size of the text. I attempted to make changes in the CSS for the font family an ...

Generate a dropdown list in real-time by pulling text from a text area

I prefer to have this coded in jquery, but I am also okay with javascript. Here is the question: I have a textarea and a dropdown menu on the same page. I can input text into the textarea by typing or pasting it. Each line in the textarea contains email ...

AJAX fails to retrieve a result

I've been attempting to grasp the concept of using ajax, but unfortunately I have not been able to receive any response. Here is the HTML code: <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta ...

Enhance TinyMCE functionality to permit text as a primary element within <table> or <tr> tags

I've been struggling for the past three hours, trying out different solutions and searching like crazy on Google. Unfortunately, I have not been able to find a resolution to this particular issue. Issue: TinyMCE is not allowing me to insert text dire ...

Can a complete form be encapsulated within a single AngularJS directive?

While I have come across several instances of individuals utilizing a blend of HTML and directives to craft an AngularJS form (as seen here), my goal is to develop a self-contained widget. This widget would encompass all the necessary HTML for the form w ...

Sliding down dropdown menu with JQuery activation on click action

This is the code I have for opening a dropdown menu $smallScreenMenu when $iconMenu1 is clicked Javascript code: const $iconMenu1 = $('#iconMenu1') const $smallScreenMenu = $('#smallScreenMenu') $($iconMenu1.on('click', ()=& ...

Unable to change the AJAX variable that was returned

I have a JavaScript/jQuery script that fetches an external HTML page using AJAX and then applies a function to all its text nodes. $.get('webpage.html', function (html) { $(html).find('*').each(function () { $(this).content ...

The specific error "Argument is not a function, got undefined" in the $broadcast function is exclusive to Angular on Firefox

An Angular error is popping up in Firefox but not in Chrome or IE. The specific error message is: Error: Argument 'myControllerName' is not a function, got undefined. When tracing the stack, it seems to be originating from the $broadcast function ...

JSON Generator's date formatting convention

One method I use to create a JSON object is through JSON-GENERATOR I prefer the date to be formatted like this: 2017-12-31 [ '{{repeat(5, 7)}}', { equityPriceList: [ { date:'{{date(new Date(1970, 0, 1), new Date(),[DD ...

What is the best way to execute the angular-phonecat tutorial tests while the server is operating without a graphical user interface?

The angular-phonecat demo assumes that your server has chrome installed and you are running it there. When you run the command npm test, the local chrome browser should launch and continuously run the tests. However, if you are using a headless server li ...

jQuery DataTables covering a CSS-anchored menu bar

My webpage has a pinned navigation menu bar at the top and some tables with interactive features using jQuery's DataTables. However, after implementing jQuery, I encountered an issue where the tables cover the menu when scrolling down, making it uncli ...

The issue I am facing is that CKEditor is inserting the <pre> tag into my

I have been attempting to input Hindi language content into my database. However, when I make an API request, the data is added in Hindi as needed but a <pre> tag is inserted. I am using CkEditor like this: <CKEditor data={this.stat ...

Retrieve tagged photos from the News Feed using the Graph API

I'm looking to access all photos from a user's newsfeed on Facebook through the Graph API. I want to retrieve not just the posted photos, but also those that the user has commented on, been tagged in, or where their friends have been tagged. Is t ...

What could be causing my JavaScript code to malfunction, even though it appears to be coded correctly?

// JavaScript Document "use strict"; $(window).scroll(function(){ if($(window).scroll() > 100){ $("#scrollTop").fadeIn(); } }); $(window).scroll(function(){ if($(window).scroll() < 100){ $("#scrollTop").fadeOut(); } }); $(document).ready(function() ...

Retrieve all files from a directory that include a specific string, store the file names in an array, and then return the array using

Exploring a new challenge, I am attempting to scan a specific directory for files that contain a particular string in their contents and compile a list of their names. Here is the code snippet I have developed up to this point: const dirname = path.res ...

How can we efficiently add a new node to a polyline link in gojs while maintaining the original positions of points in the links adjacent to the inserted node

After posting a question on StackOverflow (Seeking Javascript library for displaying and editing networks of nodes and edges), I was directed to the gojs splice sample. The sample has been helpful, but I've hit a roadblock trying to achieve the speci ...

What are the steps to design a versatile gallery page that can serve various projects?

Allow me to get straight to the point. What is my goal? I am aiming to develop galleries for various projects. Each project's thumbnail on the main page should open a gallery as a new page. These galleries will all have the same layout but different ...

Creating audio streams using react-player

I am currently working on integrating the react-player component from CookPete into my website. However, I am facing a challenge in setting up multiple audio streams. Additionally, I want to include both DASH and HLS video streams but adding them as an arr ...