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;
};

1 Answer 1

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))

Sign up to request clarification or add additional context in comments.

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.