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.
You can use indexOf to check if an element is in an array.
or use an object instead of an array if you have an unique id or name:
var output = {}