views:

58

answers:

2

Hi Everyone,

While dealing with JSON returned from YQL, I found myself looking for a way extract all unique values from an array.

function uniqueArrayValues(o){
      var items = o.query.results.row,
          output = [];

  function check(val){
    for(var c=0; c<output.length; c++){
      if(output[c] === val){
        return false;
        }
    }
     return true;
  }

 for(var i=1; i<items.length; i++){
   if(check(items[i].team)){
     output.push(items[i].team);
    }    
  }

  return output;
}

The code looks a bit too 'busy' and i was wondering if there is a more elegant way of extracting unique values from an array.

A: 

If your array has non-trivial length, the standard way to extract unique elements is to sort or to hash the array.

EDIT: Some pseudo code

sort array
last = unused
for each v in array do
  if v != last
     uniqueArray.push_back(v)
     last = v
  end if
end for
// uniqueArray now contains the unique elements of array
Peter G.
Please show me the code.
Q_the_dreadlocked_ninja
+1  A: 

You can use indexOf to check if an element is in an array.

 function check(val){
        return output.indexOf(val) != -1;
    }

or use an object instead of an array if you have an unique id or name: var output = {}

for(var i=1; i<items.length; i++){
   if(!output[items[i].team.id])){
     output [items[i].team.id] = items[i].team;
    }    
  }
eskimoblood