Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get unique objects from array based on single attribute

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.

like image 997
THE JOATMON Avatar asked Jan 12 '23 17:01

THE JOATMON


1 Answers

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/

like image 131
David Hellsing Avatar answered Jan 16 '23 18:01

David Hellsing