Puneet Sharma Puneet Sharma - 3 months ago 10
Javascript Question

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

Answer

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
}