2016-08-29 2 views
0

Die _.uniq() in lodash entfernt Duplikate aus einem Array:Lodash: Was ist das Gegenteil von `_uniq()`?

var tst = [ 
{ "topicId":1,"subTopicId":1,"topicName":"a","subTopicName1":"w" }, 
{ "topicId":2,"subTopicId":2,"topicName":"b","subTopicName2":"x" }, 
{ "topicId":3,"subTopicId":3,"topicName":"c","subTopicName3":"y" }, 
{ "topicId":1,"subTopicId":4,"topicName":"c","subTopicName4":"z" }] 

var t = _.uniq(tst, 'topicName') 

Das gibt:

[ {"topicId":1,"subTopicId":1,"topicName":"a","subTopicName1":"w" }, 
    { topicId: 2, subTopicId: 2, topicName: 'b', subTopicName2: 'x' }, 
    { topicId: 3, subTopicId: 3, topicName: 'c', subTopicName3: 'y' } ] 

Was ist das Gegenteil davon? Es sollte nur ein einzelnes Objekt für jedes Duplikat-Objekt zurückgeben:

[ { topicId: 3, subTopicId: 3, topicName: 'c', subTopicName3: 'y' } ] 
+0

Es gibt nichts, für Dies ist kein üblicher Anwendungsfall, aber Sie könnten Ihr Array filtern, alles ohne Duplikate ablehnen und dann das erste Array verwenden. – Seiyria

Antwort

1

Ich glaube nicht, dass es ein in Verfahren gebaut, hier ist etwas, das die Arbeit machen soll:

function dupesOnly(arr, field) { 
    var seen = {}, 
     ret = []; 

    arr.forEach(function(item) { 
     var key = item[field], 
      val = seen[key]; 

     if (!val) { 
      seen[key] = val = { 
       initial: item, 
       count: 0 
      } 
     } 

     if (val.count === 1) { 
      ret.push(val.initial); 
     } 
     ++val.count; 
    }); 

    return ret; 
} 
+0

OP wollte eine lodash-Lösung, also warum nicht lodash? – Seiyria

+2

Damit Sie kommentieren können "warum nicht lodash verwenden". Es funktionierte. –