SKay
SKay

Reputation: 147

Find duplicate values in javascript associative array (hash)

Have an key value pair like below

var point = [];
point["I1"] = 1000;
point["I2"] = 2000;
point["I3"] = 1000;
point["I4"] = 5000;
point["I5"] = 2000;
point["I6"] = 4000;

want to find the duplicate values, result hash should contain ONLY DUPLICATE value information.

result["1000"] = " I1,I3";
result["2000"] = "I2,I5";

duplicate values should be keys of result hash.

I sort the array, but clueless to traverse hash to check the duplicate values to build the result hash

https://fiddle.jshell.net/jbs9y896/1/

Upvotes: 1

Views: 2358

Answers (2)

Morteza Tourani
Morteza Tourani

Reputation: 3536

You can check all values with loop over keys of point. I changed your terms a little bit. You can set extra keys for Array but you'd better use an Object instead. The result for each value would be an array which can be converted to comma separated values with just a toString call on each array.

Edit

As request is edited, to contain only duplicates You can just loop again (but this time over the hash) and get which has more than one result.

var point = {
  I1: 1000,
  I2: 2000,
  I3: 1000,
  I4: 5000,
  I5: 2000,
  I6: 4000,
};

var hash = Object.create(null);
var result = Object.create(null);

Object.keys(point).forEach(k => {
  var grp = point[k];
  (grp in hash) ? hash[grp].push(k): (hash[grp] = [k]);
});

for (key in hash)
  if (hash[key].length > 1)
    result[key] = hash[key].toString();

console.log(hash['1000'].toString());
console.log(hash);
console.log(result);

Upvotes: 2

alejandromav
alejandromav

Reputation: 943

to get result["1000"] = "I1,I3" instead of result["1000"] = ['I1','I3']:

var point = {};
point["I1"] = 1000;
point["I2"] = 2000;
point["I3"] = 1000;
point["I4"] = 5000;
point["I5"] = 2000;
point["I6"] = 4000;

var hash = Object.create(null);
Object.keys(point).forEach(k => {
  var grp = point[k];    
  (grp in hash) ? hash[grp] = hash[grp] += ',' + k: (hash[grp] = k);
})

console.log(hash);

Upvotes: 1

Related Questions