Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lodash/underscore; compare two objects and remove duplicates

As you can see in the image below, I have some returned json data with three objects; each contains a clients id => data.

Returned json data

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

How can I "trim" or remove the duplicate objects based on previous ones? something like:

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

I tried _.difference but did not work (Maybe because it is for arrays not 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 help would be appreciated :)

Update

I need that the returned value has the same object data instead of a new array :)

like image 311
numediaweb Avatar asked Mar 04 '15 15:03

numediaweb


People also ask

How do I compare two objects in Lodash?

In Lodash, we can deeply compare two objects using the _. isEqual() method. This method will compare both values to determine if they are equivalent.

How do I remove duplicates in Lodash?

We can remove duplicate elements from an array using the _. uniq() method of Lodash. This method keeps the first instance of an element and removes the remaining one. Therefore, the order of an element in the resultant array depends on its occurrence in the array.

Is Deep equal Lodash?

The Lodash _. isEqual() Method performs a deep comparison between two values to determine if they are equivalent. This method supports comparing arrays, array buffers, boolean, date objects, maps, numbers, objects, regex, sets, strings, symbols, and typed arrays.


1 Answers

It looks like you want to diff keys (or rather, it'd be efficient to — _.keys)

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

Or, you could always convert your object to an array of pairs if you want to compare within the objects too (_.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]]
like image 115
Jonathan Allard Avatar answered Sep 28 '22 00:09

Jonathan Allard