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.
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;
}
}
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.