从数组中获取唯一值

时间:2014-01-29 06:58:28

标签: javascript arrays unique

var arr = ["THYROID","CARDIAC","CARDIAC,DIABETES","METABOLIC,ARTHRITIS","RENAL DISEASES,DIABETES","LIVER DISEASES,HEPATITIS","LIVER DISEASES,CANCER,METABOLIC","LIVER DISEASES,HEPATITIS,ARTHRITIS,METABOLIC"]

以上是我的代码, 我需要使用Javascript从这个数组中获取唯一的值。

喜欢,我期待的是: 如果我要求独特的价值观,它应该让我:

var arr = ["THYROID","CARDIAC","DIABETES","METABOLIC","RENAL DISEASES","LIVER DISEASES,"CANCER",ARTHRITIS","HEPATITIS"]

1 个答案:

答案 0 :(得分:1)

如果你有一个字符串数组,你可以使用这些字符串作为键来创建一个对象,然后从该对象中获取键。

创建对象

for (var t = {}, i = 0; i < arr.length; i++) 
  t[arr[i]] = 0;

从对象键创建数组

// Modern browsers only
arr = Object.keys(t);

// In older browsers you can use the polyfill from the link below,
// or just loop through the object like this:
arr = [];
for (var k in t)
  arr.push(k);

Object.keys