Utilizing lodash or underscore libraries, we can compare two objects and eliminate any duplicate entries

Looking at the image below, I have some json data that consists of three objects; each containing a client's id => data.

exact_match : {104}
match_4 :  {104, 103}
match_2 :  {104, 103, 68}

Is there a way to remove duplicate objects based on previous ones? For example:

exact_match : {104}
match_4 :  {103}
match_2 :  {68}

I attempted to use _.difference but it didn't work (Possibly because it is designed for arrays rather than objects):

var exact_match = data.exact_match,
    match_four_digits = _.difference(data.match_4, data.exact_match),
    match_two_digits = _.difference(data.match_2, data.exact_match, data.match_4),

Any assistance would be greatly appreciated :)

Update

I require that the returned value maintains the same object data instead of generating a new array :)

Answer №1

It seems like you are interested in comparing keys efficiently using lodash's _.keys.

_.difference(
  _.keys({104: 1, 102: 3, 101: 0}), // ["104", "102", "101"]
  _.keys({104: 1, 102: 3}) // ["104", "102"]
)
// [ "101" ]

Alternatively, you can convert your object to an array of pairs for comparison within the objects using _.pairs:

_.difference(
  _.pairs({104: 1, 102: 3, 101: 0}), // [["104",1], ["102",3], ["101",0]]
  _.pairs({104: 1, 102: 2}) // [["104",1], ["102",2]]
)
// [["102", 3], ["101", 0]]

Answer №2

To eliminate duplicates in your data, I recommend creating a map named unique. Start by initializing it like this: var unique = {};. Next, loop through each key in your data and check if it already exists in unique. If it does, delete the entry associated with that key to remove any duplicates.

You can extract the checking process into a separate function called alreadyFound:

var alreadyFound = function (key) {
  if (!(key in unique)) {
    unique[key] = true;
    return false;
  }
  return true;
};

Then, iterate through your data and call alreadyFound(key) for each key. If the function returns true, it means the key is a duplicate and you can proceed to delete it from the data structure.

Although options like lodash/underscore methods are available, using them could be less efficient depending on how they are implemented. The approach outlined should work in linear time without compromising performance.

For your specific situation, the complete solution would involve:

var unique = {};
// Assume I copy and pasted alreadyFound here
var alreadyFound = ...;
for (var object in data) {
  // Iterate through ids in each object within the data
  for (var id in object) {
    // Delete the id if it's a duplicate
    if (alreadyFound(id)) {
      delete object[id];
    }
  }
}

Answer №3

Thank you all for your input, I truly value the time you've taken to help.

In my continued search, I came across this informative post by a developer from Lodash which guided me in creating the following code snippet;

var data = {
  exact_match: {
    104: {
      supplier_id: 104
    }
  },
  match_four_digits: {
    104: {
      supplier_id: 104
    },
    68: {
      supplier_id: 68
    }
  },
  match_two_digits: {
    104: {
      supplier_id: 104
    },
    68: {
      supplier_id: 68
    },
    103: {
      supplier_id: 103
    },
    999: {
      supplier_id: 999
    }
  }
};

var arr_match_four_digits = _.difference(_.keys(data.match_four_digits), _.keys(data.exact_match));
var arr_match_two_digits = _.difference(_.keys(data.match_two_digits), _.keys(data.match_four_digits), _.keys(data.exact_match));

$('#output1').html(JSON.stringify(data));
$('#output2').html(JSON.stringify(_.pick(data.match_four_digits, arr_match_four_digits)));
$('#output3').html(JSON.stringify(_.pick(data.match_two_digits, arr_match_two_digits));
<script src="https://cdn.rawgit.com/lodash/lodash/3.3.1/lodash.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

data
<pre><code><div id="output1"></div></code></pre>
arr_match_four_digits
<pre><code><div id="output2"></div></code></pre>
match_two_digits
<pre><code><div id="output3"></div></code></pre>

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

Tips for integrating material UI components into jspreadsheet column headers

Hey there, I have been using a valuable tool called jSpreadsheet from to generate tables. However, I am looking to replace the default columns with material UI components. Does anyone know if this is possible and how I can achieve it? The version I am cu ...

"Data passed to a JavaScript callback function may result in an undefined

I've been experiencing some issues with callbacks and getting return data as undefined. function goodMorning(name, msg) { return `${name} ${msg}`; } function greet(name, msg, cb) { const myName = "Sairam"; console.log(`${cb(name)} ${cb(msg)} ...

What is the best way to access my backend API on a web hosting platform?

To successfully send information from a contact form through an email, I need to access my backend API. My app is deployed on a webhost called Kinghost and I have two URLs provided: the first one is the generic mywebaddr.com:port-number, and the second one ...

Accessing JSON data from a .NET web service using JQuery

Having some issues with populating events from a database using FullCalendar module. The JSON string received from a C# web service is not parsing correctly, resulting in "undefined" alerts when trying to access the data. In Firebug, the response string l ...

How come the Google Calendar API in my Chrome extension doesn't update to display new events when I refresh the page after adding them through gcal?

the query I'm facing an issue with displaying upcoming Google Calendar events on my Chrome extension using JavaScript and the Google Calendar API. The problem arises when I add new events on the Google Calendar website itself, as these events do not ...

Can I safely temporarily overwrite a prototype method in a route handler in express?

I'm currently facing a scenario where I have an object containing numerous instances of the Date data type. This object is then converted into JSON format and returned as follows: router.post('/', function () { // Some code that retur ...

Align text in the center of multiple <td> elements in a table horizontally

I have a schedule table in the form of a timetable. My goal is to have the borders between two or more consecutive tasks removed. I have achieved this. Additionally, I want the text to be centered within each cell of the table. For clarification, refer to ...

Choose an image and save the selection information for the following page (Tarot card)

I'm in the process of creating a website that showcases multiple tarot cards. The goal is for users to select the cards they're interested in and have their chosen card displayed on the next page. I've implemented some code for selecting the ...

Is it possible to incorporate an editable text feature within react-moveable? (Allowing for both dragging and editing capabilities)

In React Movable box, the text can be dragged with a left click and edited with a right click using the "contentEditable" attribute. However, on smartphones, editing seems to be disabled and only dragging is possible. <div className="move ...

Issue with $_POST['projectSubmit'] not functioning as expected

I'm having trouble with echoing a JavaScript script after hitting the submit button. Instead of working, it just closes the modal and refreshes the page. I tried using `if($_POST['projectSubmit'])` instead of enclosing it in `isset()`, but i ...

Is there a Joomla extension available that can display or conceal content upon clicking?

Looking to enhance my Joomla site by installing a plugin that allows me to toggle the visibility of content with a click, similar to how FAQ sections work on many websites. Question 1 (click here for the answer) { Details for question 1 go here } Questi ...

Dynamically and asynchronously loading numerous LinkedIn share buttons on a page

On my page, I have a grid of post thumbnails that are fetched via AJAX and can be filtered. When a user clicks on a thumbnail, a carousel opens with the selected post centered. In this carousel, each post has a LinkedIn share button integrated. The issue ...

sending parameters to a callback function that is listening for arguments

function setmclisten(message, sender, sendResponse) { console.log(data); if(message['type'] === 'startUp') { console.log(data); sendResponse(data) } } function QuarryToServer(){ chrome.runtime.onMessage.removeListener( ...

Stop users from altering the model date while typing using the ui.bootstrap.datepicker-popup

I have implemented the datepicker-popup from Angular-UI Bootstrap in my application. Currently, when the user clicks and types in the text input field, $scope.dt gets updated with each keypress, causing the cursor position to reset to the end of the strin ...

The Angular method for retrieving the child's ID when it is clicked

As a newcomer to Angular 1.0 with a background in jQuery, I am facing the following scenario: Let's imagine we have the following HTML structure : <div id="filters"> <div id="filter1">Filter 1</div> <div id="filter2"> ...

"Implementing AngularJS bidirectional data binding to dynamically link user inputs with corresponding fields

Having trouble automatically outputting data with angularJS. One of the great features of angular is two-way data binding, but I can't seem to bind input with a JSON file. What I want to achieve is if the user's input matches a key, the correspon ...

What is the procedure for inserting a key-value pair into the JSON root node and then transforming it into a table using SQL Server

I have a people table with four columns: Name, TagName, Value, and Location. I want to convert the TagName and Value into JSON format with Name and Location as the root node (Name & Location remain the same for multiple records). The desired output sh ...

Responsive DataTable in Bootstrap 5 automatically hides columns to ensure optimal display on different

Is it possible to create a responsive table using DataTable 1.13.4 and Bootstrap 5.2.3? I encountered an issue while testing the table on a mobile device (using Firefox, not an actual device) where a small horizontal scrollbar appears, causing some columns ...

An issue arises when data from the parent ajax call is being referenced

I am encountering a situation where I have nested ajax functions within each other. $.ajax({ url: '../...', type: 'POST', dataType: 'JSON', ...

Update and republish an outdated npm package

After successfully publishing an npm package, I attempted to make an update which unfortunately resulted in some issues. It seems that I made a mistake during the build process. Since it had been a year since my last update, I have forgotten the exact step ...