[Chartjs]-How can I divide this Object.values with the total?

1๐Ÿ‘

โœ…

You can see your modified codesandbox here: https://codesandbox.io/s/bar-graph-forked-vp4uk
In that case, you have to use the percentage instead of the value.

So, you have to change:

  const rounded = Object.entries(res).reduce((acc, [key, value]) => {
    return { ...acc, [key]: value.toFixed(2) };
  }, {});

to this:

  const rounded = Object.entries(res).reduce((acc, [key, value]) => {
    return { ...acc, [key]: ((value / total) * 100).toFixed(2) };
  }, {});

2๐Ÿ‘

You mean

[key]: ((value/total)*100).toFixed(2)

const data = [{
    birthdate: "Thu Aug 31 2000",
    createdDate: {
      seconds: 1630377545,
      nanoseconds: 313000000
    },
    items: {
      type2: false,
      type1: true,
      selectedItem: "car"
    },
    displayName: "Person1"
  },
  {
    birthdate: "Thu Aug 31 2000",
    createdDate: {
      seconds: 1630377545,
      nanoseconds: 313000000
    },
    items: {
      type2: true,
      type1: true,
      selectedItem: "bikes"
    },
    displayName: "Person2"
  },
  {
    birthdate: "Thu Aug 31 2000",
    createdDate: {
      seconds: 1630377545,
      nanoseconds: 313000000
    },
    items: {
      type2: true,
      type1: true,
      selectedItem: "car"
    },
    displayName: "Person3"
  },
  {
    birthdate: "Thu Aug 31 2000",
    createdDate: {
      seconds: 1630377545,
      nanoseconds: 313000000
    },
    items: {
      type2: true,
      type1: true,
      selectedItem: "motor"
    },
    displayName: "Person4"
  },
  {
    birthdate: "Thu Aug 31 2000",
    createdDate: {
      seconds: 1630377545,
      nanoseconds: 313000000
    },
    items: {
      type2: true,
      type1: true,
      selectedItem: "motor"
    },
    displayName: "Person5"
  },
  {
    birthdate: "Thu Aug 31 2000",
    createdDate: {
      seconds: 1630377545,
      nanoseconds: 313000000
    },
    items: {
      type2: true,
      type1: true,
      selectedItem: "truck"
    },
    displayName: "Person6"
  },
  {
    birthdate: "Thu Aug 31 2000",
    createdDate: {
      seconds: 1630377545,
      nanoseconds: 313000000
    },
    items: {
      type2: true,
      type1: true,
      selectedItem: "bikes"
    },
    displayName: "Person7"
  },
  {
    birthdate: "Thu Aug 31 2000",
    createdDate: {
      seconds: 1630377545,
      nanoseconds: 313000000
    },
    items: {
      type2: true,
      type1: true,
      selectedItem: "truck"
    },
    displayName: "Person8"
  }
];

const total = 12;

let res = [...data].reduce(
  (a, c) => (
    (a[c.items.selectedItem] = (a[c.items.selectedItem] || 0) + 1), a
  ), {}
);

const rounded = Object.entries(res).reduce((acc, [key, value]) => {
  return { ...acc,
    [key]: ((value/total)*100).toFixed(2)
  };
}, {});

console.log(rounded)
console.log(res)

Leave a comment