0

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.

Q_Mlilo
  • 1,729
  • 4
  • 23
  • 26
  • You can filter to unique values within the YQL query, if that is an option for you. See http://developer.yahoo.com/yql/guide/sorting.html --- something like `| unique(field="row.team")` (the field maybe different, depending on the result structure). – salathe Jul 22 '10 at 12:02
  • That would work if i only needed the unique values, but i am extracting these values from an object that is already on the client side (I only make one YQL request). – Q_Mlilo Jul 22 '10 at 13:39
  • @Q, fair enough. [eskimoblood's](http://stackoverflow.com/questions/3308257/array-unique-values/3308650#3308650) answer should help you out. – salathe Jul 22 '10 at 14:44

2 Answers2

1

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;
    }    
  }
Andreas Köberle
  • 106,652
  • 57
  • 273
  • 297
-1

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.
  • 14,786
  • 7
  • 57
  • 75