Hi
I have a javascript array object rapresenting the amount of items sold in a given country, like this:
var data = [{'c1':'USA', 'c2':'Item1', 'c3':100},
{'c1':'Canada', 'c2':'Item1', 'c3':120},
{'c1':'Italy', 'c2':'Item2', 'c3':140},
{'c1':'Italy', 'c2':'Item2', 'c3':110}]
I need to avoid duplicates (as you may see, the last two ‘records’ have the same Country and the same Item) and sum the amounts; if I was getting data from a database I would use the DISTINCT SUM clause, but what about it in this scenario? Is there any good jquery trick?
You could use an object as a map of distinct values, like this:
How that works: JavaScript objects are maps, and since access to properties is an extremely common operation, a decent JavaScript implementation tries to make property access quite fast (by using hashing on property keys, that sort of thing). You can access object properties using a string for their name, by using brackets (
[]), soobj.fooandobj["foo"]both refer to thefooproperty ofobj.And so:
c1andc2. It’s important that the “–sep–” string be something that cannot appear inc1orc2. If case isn’t significant, you might throw a.toLowerCasein there.distinctsalready has a value for that key, we know we’ve seen it before and we can ignore it; otherwise, we add a value (truein this case, but it can be just about anything other thanfalse,undefined,0, or"") as a flag indicating we’ve seen this unique combination before. And we addc3to the sum.But as someone pointed out, your last two entries aren’t actually the same; I’m guessing that was just a typo in the question…