1

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/

2 Answers 2

2

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);

Sign up to request clarification or add additional context in comments.

6 Comments

Like to have only the duplicate values . The duplicate values in Point[] are 1000 and 2000. want to have only duplicate data in hash[]
@SKay It is simple to find out how to get what you want out of hash. BTW I've added result.
Got it, i want to understand this line (grp in hash) ? hash[grp].push(k): (hash[grp] = [k]); mainly the else part.
@SKay This is kind of if statement syntax. if there is a key in hash with value of grp then push new value into hash[grp] else set hash[grp] to an array with value of k.
@mortesaT thanks . [k] means value added to array. new to me! will appreciate if there is any links to know on javascript on hash and more. thanks.
|
1

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.