从数组中获取唯一值

时间:2016-09-05 02:39:03

标签: javascript jquery

所以我有2个像这样的数组...

var browser_names = ["Firefox", "Maxthon", "Opera", "Opera", "Chrome", "Chrome", "Edge", "Firefox"]

var user_count = [3, 3, 3, 3, 7, 20, 94, 142]

我想要这样的结果

var result_browser_names = ["Firefox", "Maxthon", "Opera", "Chrome", "Edge"]

var result_user_count = [145, 3, 6, 27, 94]

正如您所见,' result_browser_names '包含唯一的浏览器名称值& ' result_user_count '包含每种浏览器的“用户总数”。

我见过this解决方案,适用于单个阵列。在我的情况下,我有2个阵列......

非常感谢任何帮助。感谢

2 个答案:

答案 0 :(得分:1)

我建议使用一个物体。假设您的2个数组的长度始终匹配:

var browser_names = ["Firefox", "Maxthon", "Opera", "Opera", "Chrome", "Chrome", "Edge", "Firefox"]
var user_count = [3, 3, 3, 3, 7, 20, 94, 142]
var lib = {}

for (var i=0; i < browser_names.length; i++) {
  if (lib[browser_names[i]] != undefined) {
    lib[browser_names[i]] += user_count[i];
  } else {
    lib[browser_names[i]] = user_count[i];
  }
}

这应该为您提供浏览器名称和对象lib中保存的每个浏览器的累计用户数

此外,对于循环中的if条件,您还可以执行:

for (var i=0; i < browser_names.length; i++) {
  if (lib.hasOwnProperty(browser_names[i])) {
    lib[browser_names[i]] += user_count[i];
  } else {
    lib[browser_names[i]] = user_count[i];
  }
}

另外,我知道你的原始问题是数组的输出。您可以轻松遍历对象的键,以获取各自的浏览器名称和用户计数:

for (var k in lib) {
  console.log(k);         // Browser Names
  console.log(lib[k]);    // Their respective user counts
}

答案 1 :(得分:0)

您可以使用单个循环和对象的帮助作为结果数组的引用。

&#13;
&#13;
var browser_names = ["Firefox", "Maxthon", "Opera", "Opera", "Chrome", "Chrome", "Edge", "Firefox"],
    user_count = [3, 3, 3, 3, 7, 20, 94, 142],
    result_browser_names = [],
    result_user_count = [];

browser_names.forEach(function (b, i) {
    if (!(b in this)) {
        this[b] = result_browser_names.push(b) - 1;
        result_user_count.push(0);
    }
    result_user_count[this[b]] += user_count[i];
}, Object.create(null));

console.log(result_browser_names);
console.log(result_user_count);
&#13;
.as-console-wrapper { max-height: 100% !important; top: 0; }
&#13;
&#13;
&#13;