javascriptarrayspercentage

JS Find percentage of items in an array


So I have this array:

const colors = ['blue', 'blue', 'red', 'red', 'red', 'green', 'green', 'white']

I want to output the percentage of the similar items using JavaScript.

Such as blue and green should be 25% each, red 37.5% and white 12.5% out of total of 8(100%) items in the array.

How do I achieve that?


Solution

  • You will first need to find each unique color, then iterate over them to find how many there are. Once you have this you can calculate the percentage as (num * 100 / total).

    Take a look at this:

    const colors = ['blue', 'blue', 'red', 'red', 'red', 'green', 'green', 'white']
    
    const totalItems = colors.length
    const uniqueItems = [...new Set(colors)]
    uniqueItems.forEach(currColor => {
      const numItems = colors.filter(color => color === currColor) 
      console.log(`color ${currColor} represents ${numItems.length * 100 / totalItems}%`)
    })
    /*
    color blue represents 25%
    color red represents 37.5%
    color green represents 25%
    color white represents 12.5%
    */