3

I want to fetch an object array, check if multiple properties are duplicate at the same time. Finally, the duplicate elements are meant to be alerted. i.e. for the array:

[
  {
    "language" : "english",
    "type" : "a",
    "value" : "value1"
  },
  {
    "language" : "english",
    "type" : "a",
    "value" : "value2"
  },
  {
    "language" : "english",
    "type" : "b",
    "value" : "value3"
  },    
  {
    "language" : "spanish",
    "type" : "a",
    "value" : "valor1"
  }
];

The alert should be: "Too many elements with language english and type a".

I sought for it, yet the answers were either dirty map/reduce implementations that made VisualStudio2015 pissed off or finding a full duplicates (not only based on specific properties)

vahdet
  • 6,357
  • 9
  • 51
  • 106
  • What if there are several duplicates on several language/type pairs? Do you want to alert on the first duplicate found or all of them? – Arnauld Jul 31 '16 at 20:13
  • I want all of them prompted. – vahdet Jul 31 '16 at 20:27
  • The solution you accepted is just hard-coded... It doesn't find duplicate properties, but just hard-codes that they are duplicate, see the `console.log`. – nicael Aug 01 '16 at 06:23
  • @user4636715 Please let me know if I misread the question. It is not obvious to me that the duplicate properties need to be found dynamically. By reading it again, I see that it can be understood that way, though. – Arnauld Aug 01 '16 at 07:53
  • @Arnauld It is enough for me to alert the message indeed. I am going to ask the data provider to re-send the list to me where there are no duplicates. Hence, your way works for me anyway – vahdet Aug 03 '16 at 11:22

1 Answers1

0

Performance wise, I think the best option is to iterate on each element of the list while updating a counter of the encountered keys.

You want to alert when counter == 2. You should not test counter > 1 because it would repeat the same alert several times, when you have more than 2 pairs with the same language and same type.

var list = [{
    "language" : "english",
    "type" : "a",
    "value" : "value1"
  },{
    "language" : "english",
    "type" : "a",
    "value" : "value2"
  },{
    "language" : "english",
    "type" : "a",
    "value" : "value3"
  },{
    "language" : "english",
    "type" : "b",
    "value" : "value3"
  },{
    "language" : "spanish",
    "type" : "a",
    "value" : "valor1"
  },{
    "language" : "spanish",
    "type" : "a",
    "value" : "valor2"
}];

var counter = {};

list.forEach(function(o) {
  var key = o.language + '|' + o.type;
  if((counter[key] = (counter[key] || 0) + 1) == 2) {
    console.log('Too many elements with language '+o.language+' and type '+o.type);
  }
});
Arnauld
  • 5,847
  • 2
  • 15
  • 32