1

I have array like below

myArray = ["foo", "bar", "foo", "bar", "bar", "bar", "zoom"]

I want output like this

nameArray = ["foo", "bar", "zoom"] 

and

qtyArray = [2, 4, 1]

I will be using Plotly out of resulting two arrays to draw bar plot.

TIA

Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
snaseer
  • 13
  • 3

3 Answers3

2

You could take a Map and get the keys and values.

var array = ["foo", "bar", "foo", "bar", "bar", "bar", "zoom"],
    map = array.reduce((m, v) => m.set(v, (m.get(v) || 0) + 1), new Map),
    values = [...map.keys()],
    counts = [...map.values()];

console.log(...values);
console.log(...counts);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

You can use reduce function. Inside the callback check if the accumulator object have a key by name of foo or bar or zoom. If it is there then increase the count by 1 else create a key by that name and put 1 as value. Then you can use Object.keys to create an array of keys which will be foo,bar & zoom & Object.values to get an array of the counts

let myArray = ["foo", "bar", "foo", "bar", "bar", "bar", "zoom"];

let newData = myArray.reduce(function(acc, curr) {
  if (acc[curr]) {
    acc[curr] += 1;
  } else {
    acc[curr] = 1;

  }
  return acc;
}, {});

let nameArray = Object.keys(newData);
let qtyArray = Object.values(newData);
console.log(nameArray, qtyArray)
brk
  • 48,835
  • 10
  • 56
  • 78
0
var myArray = ["foo", "bar", "foo", "bar", "bar", "bar", "zoom"]; 
var arr = {}
myArray.map(function(x){
  if(typeof(arr[x])=="undefined") {arr[x] =0;}
  arr[x]++;
})

var arr1 = Object.keys(arr);
arr2 = arr1.map(x=>arr[x])


/* arr1
foo,bar,zoom
*/

/* arr2
2,4,1
*/
jidexl21
  • 609
  • 7
  • 22