0
var pr = {
    name: "ball",
    race: "ball",
    weapon: "axe",
};

var save=new Object;
var keys=Object.keys(pr);

for(var k in pr) { 

}
console.log(save); // should end up with {name:'ball',race:'ball'}
1
  • What if there are multiple sets of the same values (like there is a second axe)? Commented Aug 16, 2018 at 16:11

4 Answers 4

1

If I have understood the question correctly, one option is:

const keys = Object.keys(pr);
const ret = keys.reduce((ret, k, i) => {
  const f = keys.find((k2, i2) => i !== i2 && pr[k] === pr[k2]);
  if (f) ret[k] = pr[k];
  return ret;
}, {});
Sign up to request clarification or add additional context in comments.

Comments

0

Here is what I came up with.

var pr = {
  name: "ball",
  race: "ball",
  weapon: "axe"
};

const dupValues = Object.values(pr).reduce(
  (acc, cur) => ({ ...acc, [cur]: (acc[cur] || 0) + 1 }),
  {}
);

const result = Object.keys(pr)
  .filter(key => dupValues[pr[key]] > 1)
  .reduce((acc, curr) => ({ ...acc, [curr]: pr[curr] }), {});

console.log(result);
// {name:'ball',race:'ball'}

Comments

0

One way to do it is use the save object as a histogram, keeping track of duplicates. Then, filter out any keys with 0 count using reduce. This should have better performance than a linear function like find:

var pr = {
  name: "ball",
  race: "ball",
  weapon: "axe"
};
var save = {};

for (var k in pr) {
  save[pr[k]] = pr[k] in save ? save[pr[k]] + 1 : 0;
}

var result = Object.keys(pr).reduce((a, e) => {
  if (save[pr[e]]) { a[e] = pr[e]; }
  return a;
}, {});

console.log(result);

Comments

0

It works. Simple and clear. References : Array.reduce()

Iterate through each key value pair, and accumulate the result until the loop ends.

var pr = {
    name: "ball",
    race: "ball",
    weapon: "axe",
    item:"bat",
    newitem:"bat",
    newweapon: "axe"
};

var result = Object.keys(pr).reduce(function(acc, key){
    var ispresent = false;
    acc.forEach(function(obj,i){
        if(ispresent) return;
        if(Object.values(obj)[0]===pr[key])
        {
            obj[key]=pr[key];
            ispresent = true;
        }
    });
    if(!ispresent)
    {
        var newobj = {};newobj[key]=pr[key];
        acc.push(newobj)
    }
    return acc;
},[])

console.log(result)

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.