Getting unique objects from an array based on a single attribute

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 source nodes, because they all have a different name or color. I only want to get nodes with a unique name that should return

node[1] (apple)
node[2] (cherry)
node[4] (orange)

He should not return 3, because it is the same fruit, although we have green and red apples.

+4
source share
3 answers

Use a Array.filtertemporary array to store duplicates:

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/

+7
source

(forked from @David's) ( object[] - 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/

+2

How to do it?

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 like that.

0
source

All Articles