Get unique objects from array based on single attribute

Deadly 提交于 2019-12-12 11:23:47

问题


Let's say we have the following:

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;

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)

It should not return 3 because it is the same fruit, even though we have green and red apples.


回答1:


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)
  })
}

Demo: http://jsfiddle.net/mbest/D6aLV/6/




回答2:


This approach (forked from @David's) should have better performance for large inputs (because object[] is O(1)).

function filter(arr, attribute) {
  var out = [],
      seen = {}

  return arr.filter(function(n) {
      return (seen[n[attribute]] == undefined) 
              && (seen[n[attribute]] = 1);
  })
}

console.log(filter(node, 'name'));

http://jsfiddle.net/LEBBB/1/




回答3:


What about doing it like this?

var fruitNames = [];
$.each($.unique(fruits), function(i, fruit) {
    if (fruitNames.indexOf(fruit.name) == -1) {
        fruitNames.push(fruit.name);
        $('#output').append('<div>' + fruit.name + '</div>');
    }
});

Here is a working fiddle.

Obviously, instead of output.append I could just add the current fruit to uniqueFruit[] or something.



来源:https://stackoverflow.com/questions/20480391/get-unique-objects-from-array-based-on-single-attribute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!