1

I am trying to sort an array and concat data with the same "date" value together into an array.

So far I tried .map/.foreach method to loop around date variable and group all the other property as an object, but I get confused on how to combine data with the same data key.

Data I am working on :

let rawdata = [ { 'date': 'a', 'time': 'b', 'value1': 123, 'value2': 234 },
  { 'date': 'a', 'time': 'c', 'value1': 127, 'value2': 294 },
  { 'date': 'b', 'time': 'c', 'value1': 127, 'value2': 294 }]

My goal:

target = [ { 'date': 'a', 
             'data': [{ 'time': 'b', 'value1': 123, 'value2': 234 }, 
                      { 'time': 'c', 'value1': 127, 'value2': 294 }] },
           { 'date': 'b', 
               data: [{ 'time': 'c', 'value1': 127, 'value2': 294 }] }]

What I did:

let data1 = rawdata.map(item => {
  return {
    date: item.date,
    data: [
      { time: item.time,
        value1: item.value1,
        value2: item.value2
      }
    ]
  }
})

How to concat data1 sorting by the key of date?

2

1 Answer 1

1

Use reduce:

let rawdata = [ { 'date': 'a', 'time': 'b', 'value1': 123, 'value2': 234 },{ 'date': 'a', 'time': 'c', 'value1': 127, 'value2': 294 },{ 'date': 'b', 'time': 'c', 'value1': 127, 'value2': 294 }];
let target = Object.values(rawdata.reduce((acc, { date, ...rest }) => {
  if (acc[date]) {
    acc[date].data.push({...rest});
  } else {
    acc[date] = { date, data: [{ ...rest }] };
  }
  return acc;
}, {}));
console.log(target);
.as-console-wrapper { max-height: 100% !important; top: auto; }

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

1 Comment

No worries @LWang, always glad to help. If my answer fixed your problem please mark it as accepted.

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.