0

I have two arrays. First array is an array of object with each object respresenting a vote for an item, the id represents the item that was voted.

The second array contains all the options for that poll.

I want to create a new array with each option from the poll options with a new attribute having the percentage of votes they got from the votes array.

This is the votes array.

votes = [{ 
 vote_id: 1, person: {name: ‘alan’}
}, {
 vote_id: 2, person: {name: ‘John’}
},{ 
 vote_id: 1, person: {name: ‘khan’}
}, { 
vote_id: 1,  person: {name: ‘martin’}
},{ 
vote_id: 3, person: {name: ‘mike’}
}]
Options = [{
id: 1, title: ’sweet’}, {
id: 2: ’salty’}, {
id: 3, title: ’spicy’}, {
id: 4, title: ’bitter’}]

This is the new array that I want to create from the data available from the above two arrays

new array = [{
Id: 1, title: ’sugar’, percentage: 60%},
{Id: 2, title: ’salt’, percentage: 20% },
{id: 3, title: ’spice’, percentage: 20%},
{id: 4, title: ‘bitter’, percentage: 0%}]

1 Answer 1

2

Separate the problem into two parts:

  1. get the counts,
  2. map percentage.

const
    votes = [{ vote_id: 1, person: { name: 'alan' } }, { vote_id: 2, person: { name: 'John' } }, { vote_id: 1, person: { name: 'khan' } }, { vote_id: 1, person: { name: 'martin' } }, { vote_id: 3, person: { name: 'mike' } }],
    options = [{ id: 1, title: 'sweet' }, { id: 2, title: 'salty' }, { id: 3, title: 'spicy' }, { id: 4, title: 'bitter' }],
    counts = votes.reduce((r, { vote_id }) => {
        r[vote_id] = (r[vote_id] || 0) + 1;
        return r;
    }, {}),
    result = options.map(o => ({ ...o, percentage: ((counts[o.id] || 0) * 100 / votes.length).toString() + ' %' }));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

1 Comment

there's a slight modification in the question, can you please adjust the solution according to the modification

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.