0

so I have this array.

["2020-01-31 18:31:01", "2020-02-03 14:04:30", "2020-02-04 05:58:48", "2020-02-04 14:11:16"]

and I like to convert it to object.

0: {date: "2020-01-31", time: ["8:31:01"]}
1: {date: "2020-02-03", time: ["4:04:30"]}
2: {date: "2020-02-04", time: ["5:58:48", "14:11:16"]}

But I 'm getting this result

0: {date: "2020-01-31", time: "8:31:01"}
1: {date: "2020-02-03", time: "4:04:30"}
2: {date: "2020-02-04", time: "5:58:48"}

This is my code

var times = response.data.time;
var dates = [];
var t = [];
var d = '';
var newData = [];
times.forEach(time => {

   var da = time.substring(0, 10);
   var ti = time.substring(12, 19);

   if(d == da) {

     t.push(ti);

   } else {

     d = da

     var dt = {date: da, time: ti};
     newData.push(dt);

   }


 });

I'm having a hard time to figure this out hope you can help me.

Thanks.

user123
  • 435
  • 1
  • 6
  • 23

2 Answers2

5

Try to use Array.prototype.reduce function:

const array = ["2020-01-31 18:31:01", "2020-02-03 14:04:30", "2020-02-04 05:58:48", "2020-02-04 14:11:16"];

const newData = array.reduce((acc, cur) => {
 const [date, time] = cur.split(' ');
 const dateObj = acc.find(e => e.date === date);
 if (dateObj) {
  dateObj.time.push(time);
 } else {
  acc.push({ date, time: [time] });
 }
 return acc;
}, []);

console.log(newData);
Hao Wu
  • 17,573
  • 6
  • 28
  • 60
3

Almost a copy of Hao Wu's solution, but faster, as it does not rely on linear find. The values are accumulated into an object, allowing for fast lookups, and then an array is extracted using Object.values:

const array = ["2020-01-31 18:31:01", "2020-02-03 14:04:30", "2020-02-04 05:58:48", "2020-02-04 14:11:16"];

const newData = Object.values(array.reduce((acc, cur) => {
 const [date, time] = cur.split(' ');
 if (!acc[date]) {
    acc[date] = { date, time: [] };
  }
  acc[date].time.push(time);
 return acc;
}, {}));

console.log(newData);
Amadan
  • 191,408
  • 23
  • 240
  • 301