Home > Mobile >  JS: Arrange object data based on occurrences
JS: Arrange object data based on occurrences

Time:03-17

I need to somehow arrange the data below to a certain format like below:

  const data: {} = [
    { emotion: 3, intensity: 1 },
    { emotion: 5, intensity: 2 },
    { emotion: 3, intensity: 1 },
    { emotion: 3, intensity: 2 },
  ]

  const dataone = _.groupBy(data, 'emotion')

  const entries: any = Object.entries(dataone)
  console.log(entries)

To this format:

 [{emotion: 3, 1: 2, 2: 1, total: 3},
 {emotion: 5, 1: 0, 2: 1, total: 1}]

Would appreciate it if you could provide any help or link to some similar questions.

CodePudding user response:

You could group and update the values.

const
    data = [{ emotion: 3, intensity: 1 }, { emotion: 5, intensity: 2 }, { emotion: 3, intensity: 1 }, { emotion: 3, intensity: 2 }],
    result = Object.values(data.reduce((r, { emotion, intensity }) => {
        r[emotion] ??= { 1: 0, 2: 0, emotion, total: 0 };
        r[emotion][intensity]  ;
        r[emotion].total  ;
        return r;
    }, {}));

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

  • Related