数组唯一值 [英] Array unique values

查看:152
本文介绍了数组唯一值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在处理从YQL返回的JSON时,我发现自己正在寻找一种从数组中提取所有唯一值的方法.

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.

推荐答案

您可以使用indexOf来检查元素是否在数组中.

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

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

,或者如果您具有唯一的ID或名称,则使用对象而不是数组: var output = {}

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;
    }    
  }

这篇关于数组唯一值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆