从基于单个属性的数组中获取唯一对象 [英] Get unique objects from array based on single attribute
本文介绍了从基于单个属性的数组中获取唯一对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我们有以下内容:
node[1].name = "apple";
node[1].color = "red";
node[2].name = "cherry";
node[2].color = "red";
node[3].name = "apple";
node[3].color = "green";
node[4].name = "orange";
node[4].color = "orange;
如果我使用jQuery.unique(我将获得所有原始节点,因为它们都有不同的名称或颜色。我想要做的只是获取具有唯一名称的节点,该节点应返回
if I use jQuery.unique(node) I will get all the original nodes because they all have a different name OR color. What I want to do is only get the nodes with a unique name, which should return
node[1] (apple)
node[2] (cherry)
node[4] (orange)
它不应该返回3,因为它是相同的水果,即使我们有绿色和红色的苹果。
It should not return 3 because it is the same fruit, even though we have green and red apples.
推荐答案
使用 Array.filter
和一个临时数组来存储副本:
Use Array.filter
and a temporary array to store the dups:
function filterByName(arr) {
var f = []
return arr.filter(function(n) {
return f.indexOf(n.name) == -1 && f.push(n.name)
})
}
演示: http://jsfiddle.net/mbest / D6aLV / 6 /
这篇关于从基于单个属性的数组中获取唯一对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文