Javascript Array in a specific order, adding 0 to no value

Viewed 57

I'm trying to use charts.js, but to insert the values I need them in a specific order.

First I have this array, that contains the members in order:

members = ['john', 'elise', 'mark']

And I also have a code that gives me this return:

membersReturn = ['john', 'john', 'john', 'john', 'mark', 'mark']

So I need to have a result like this:

result = [4,0,2] //4 of john, 0 of elise and 2 of mark.

The order of the members needs to be the same and add 0 for no value.

2 Answers

You could just filter and count the results

let members = ['john', 'elise', 'mark'];
let membersReturn = ['john', 'john', 'john', 'john', 'mark', 'mark'];
let result = members.map(n => membersReturn.filter(nm => nm === n).length)
console.log(result)

You can hold all results in object for better complexity:

let members = ['john', 'elise', 'mark'];
let membersReturn = ['john', 'john', 'john', 'john', 'mark', 'mark'];

const dictionary = {}
membersReturn.forEach((item) => dictionary[item] =  dictionary[item] ? ++dictionary[item] : 1)

const results = members.map(item => dictionary[item] || 0)

console.log(results)

Related