1

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 2

3

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)

Sign up to request clarification or add additional context in comments.

Comments

2

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.