Javascript - 清除数组对象的重复项 [英] Javascript - clearing duplicates from an array object
问题描述
嗨
我有一个javascript数组对象,代表在给定国家/地区销售的商品数量,如下所示:
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}]
我需要避免重复(如你可能会看到,最后两个'记录'具有相同的国家和相同的项目)并将金额相加;如果我从数据库获取数据,我将使用DISTINCT SUM子句,但在这种情况下呢?有没有什么好的jquery技巧?
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:
var distincts, index, sum, entry, key;
distincts = {};
sum = 0;
for (index = 0; index < data.length; ++index) {
entry = data[index];
key = entry.c1 + "--sep--" + entry.c2;
if (!distincts[key]) {
distincts[key] = true;
sum += entry.c3;
}
}
如何运作: JavaScript对象是映射,并且由于对属性的访问是极常见操作,因此一个不错的JavaScript实现试图使属性访问非常快(通过在属性键上使用散列,这种事情)。您可以使用括号( []
)使用字符串作为名称来访问对象属性,所以 obj.foo
和 obj [foo]
都引用 obj $的
foo
属性c $ c>。
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 ([]
), so obj.foo
and obj["foo"]
both refer to the foo
property of obj
.
所以:
- 我们从一个对象开始没有属性。
- 当我们遍历数组时,我们从
c1
和c2 <创建唯一键/ code>。重要的是--sep--字符串是不能出现在
c1
或c2 $中的字符串C $ C>。如果情况不重要,您可以在那里抛出
.toLowerCase
。 - 如果
区分
已经有一个该键的值,我们知道我们之前已经看过它,我们可以忽略它;否则,我们在这种情况下添加一个值(true
,但它可以是false
以外的任何其他值,undefined
,0
,或)作为标志指示我们之前见过这种独特的组合。我们将
c3
添加到总和中。
- We start with an object with no properties.
- As we loop through the array, we create unique key from
c1
andc2
. It's important that the "--sep--" string be something that cannot appear inc1
orc2
. If case isn't significant, you might throw a.toLowerCase
in there. - If
distincts
already has a value for that key, we know we've seen it before and we can ignore it; otherwise, we add a value (true
in 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 addc3
to 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...
这篇关于Javascript - 清除数组对象的重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!