How to ReMap an array of object into new array

Viewed 196

I have this initial array:

const initialData = [
  {
    day: 1,
    values: [
      {
        name: 'Roger',
        score: 90,
      },
      {
        name: 'Kevin',
        score: 88,
      },
      {
        name: 'Steve',
        score: 80,
      },
    ],
  },
  {
    day: 2,
    values: [
      {
        name: 'Roger',
        score: 70,
      },
      {
        name: 'Michael',
        score: 88,
      },
    ],
  },
  {
    day: 3,
    values: [
      {
        name: 'Steve',
        score: 97,
      },
    ],
  },
];

to be converted into:

const result = [
  {
    name: 'Roger',
    scores: [90, 70, null],
  },
  {
    name: 'Kevin',
    scores: [88, null, null],
  },
  {
    name: 'Steve',
    scores: [80, null, 97],
  },
  {
    name: 'Michael',
    scores: [null, 88, null],
  },
];

I'm trying to use array map and create temporary array:

const holder = [];

initialData.map()

but to no avail

2 Answers

You can do this in a couple of steps - first reduce so you can index by name, and then map those entries to the format you expected

const initialData = [{day:1,values:[{name:"Roger",score:90},{name:"Kevin",score:88},{name:"Steve",score:80}]},{day:2,values:[{name:"Roger",score:70},{name:"Michael",score:88}]},{day:3,values:[{name:"Steve",score:97}]}];


var result = Object.entries(initialData.reduce( (acc,item) => {
  item.values.forEach( v => {
    if(!acc[v.name]) acc[v.name] = {};
    acc[v.name][item.day] = v.score;
  });
  return acc;
},{})).map( ([name,days]) => ({  
    name,
    scores: new Array(initialData.length).fill(null).map( (_,i) => days[i+1] || null)
}))

console.log(result);

You could use reduce and forEach to create one object for each name and then to get an array from that object you can just use Object.values method.

const data = [{"day":1,"values":[{"name":"Roger","score":90},{"name":"Kevin","score":88},{"name":"Steve","score":80}]},{"day":2,"values":[{"name":"Roger","score":70},{"name":"Michael","score":88}]},{"day":3,"values":[{"name":"Steve","score":97}]}]

const obj = data.reduce((r, { values }, i) => {
  values.forEach(({ name, score }) => {
    if (!r[name]) r[name] = { name, scores: Array(data.length).fill(null)}
    r[name].scores[i] = score
  })
  
  return r;
}, {})

const result = Object.values(obj)

console.log(result)

Related