I've got an object like:
{
a : 'foo',
b : 'bar',
c : 'foo',
d : 'baz',
e : 'bar'
}
I want to reduce the duplicates like:
{
ac : 'foo',
be : 'bar',
d : 'baz'
}
What's a good way to do that?
A few caveats:
var Reduce = function(obj)
{
var temp = {};
var val = "";
for (var prop in obj)
{
val = obj[prop];
if (temp[val])
temp[val] = temp[val] + prop.toString();
else
temp[val] = prop.toString();
}
var temp2 = {};
for (var prop in temp)
{
val = temp[prop];
temp2[val] = prop.toString();
}
return temp2;
};
Use as:
var obj = {
a :"foo",
b : "bar",
c : "foo",
d : "bar",
e : "bar"
};
var ob2 = Reduce(obj);
This is the shortest I could get it:
var obj, newObj = {}; // obj is your original
for (var i in obj) {
if (!obj.hasOwnProperty(i)) continue;
for (var j in newObj) {
if (newObj.hasOwnProperty(j) && newObj[j] === obj[i]) break;
j = "";
}
newObj[i + j] = obj[i];
j && delete newObj[j];
}
Explanation:
obj
, and produces a new object, newObj
.newObj
for the same value. - The result is j
, either the name of the property if found, or an empty string if not. j
.newObj
if there was one, to prevent duplicates being constructed.Admittedly, setting j = ""
within the loop is inefficient. This can easily be replaced with a second variable set to ""
initially, and j
only if a match is found. I decided to go for simplicity though.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With