简体   繁体   中英

Getting Unique value from an array

So I have 2 arrays like these ...

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

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

I want results like these

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

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

As you can see ' result_browser_names ' contains unique browser name values & ' result_user_count ' contains 'sum of users' for each type of browser.

I have seen this solution, which works great for a single array. In my case I have 2 arrays ....

Any help is very much appreciated. Thanks

I'd suggest using an object. Assuming your 2 arrays will always match in length:

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

This should give you the browser names and the cumulative user counts for each browser saved within object lib

Also, for the if conditional in the loop, you could also do:

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

Also, I know your original question was an output to an array. You can easily loop through the keys of the object to get each of their respective browser names and user counts as well:

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

You could use a single loop and the help from an object as reference to the result arrays.

 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); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM