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.

2 Answers 2

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

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

Comments

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

Comments

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.