1

I need help implementing the following function definition:

I don't know how to deal with multidimensional arrays as such

input (grouped by date)

[
  {date: 1552489200000, data: [{id: 1, value:100}, {id: 2, value: 101}]},
  {date: 1552575600000, data: [{id: 1, value:102}, {id: 2, value: 103}]},
  {date: 1552662000000, data: [{id: 1, value:104}]},
]

output (group by Id)

[
  {id:1, data: [{date: 1552489200000, value: 100}, {date: 1552575600000, value: 102}, {date: 1552662000000, value: 104}]},
  {id:2, data: [{date: 1552489200000, value: 101}, {date: 1552575600000, value: 103}]},
]

const changeDataOrg = (
  groupByDate: { date: number; data: { id: number; value: number }[] }[],
): { id: number; data: { date: number; value: number }[] }[] => {
  const groupById = [];
  return groupById;
};
adiga
  • 34,372
  • 9
  • 61
  • 83
d.Foo
  • 63
  • 9

1 Answers1

3

You can use reduce and forEach

We create key based on id and kepp pushing the values accordingly in. if key is already there than we push new entry in data array of particular key if not than we add a new key with value. In the end we take out values from the output object.

let data = [{date: 1552489200000, data: [{id: 1, value:100}, {id: 2, value: 101}]},{date: 1552575600000, data: [{id: 1, value:102}, {id: 2, value: 103}]},{date: 1552662000000, data: [{id: 1, value:104}]},]

let output = data.reduce((out,{date, data})=>{
  data.forEach(({id, value }) => {
    let data = {date,value}
    out[id] ? out[id].data.push(data) : out[id]={id,data:[data]}
  })
  return out
},{})

console.log(Object.values(output))
Code Maniac
  • 37,143
  • 5
  • 39
  • 60
  • sorry I forgot to click that , I just did now , I am sorry to ask for that but can you add some comments to the code so its easier for me to understand? thank you so much – d.Foo Feb 17 '19 at 03:37