Ozan Mudul
Ozan Mudul

Reputation: 1010

JavaScript splitting string by date and grouping in array

well I have this array

let a = ["2020-09-13 10:00", "2020-09-13 11:00", "2020-09-14 10:00"];

and I want it to order like

{"2020-09-13": ["10:00","11:00"]},
{"2020-09-14": ["10:00"]}

I tried anything comes to my mind but I think I am a bit rusty, could you guys please bear a hand?

Upvotes: 0

Views: 177

Answers (2)

Derek Wang
Derek Wang

Reputation: 10193

Using String.split, you can split the date & time value.

And using Array.reduce, you can group by the date value key.

const a = ["2020-09-13 10:00", "2020-09-13 11:00", "2020-09-14 10:00"];
const result = a.reduce((acc, cur) => {
  const timeArr = cur.split(' ');
  acc[timeArr[0]] ? acc[timeArr[0]].push(timeArr[1]) : acc[timeArr[0]] = [ timeArr[1] ];
  return acc;
}, {});
console.log(result);

Upvotes: 0

Tornike Kechakmadze
Tornike Kechakmadze

Reputation: 46

let a = ["2020-09-13 10:00", "2020-09-13 11:00", "2020-09-14 10:00"];

const result = a.map(elem => elem.split(" ")).reduce((accm, elem) => {
    const date = elem[0];
    const time = elem[1];

    let accmValues = accm[date];
    if (!accmValues) {
        accmValues = []
    }

    accmValues.push(time)

    accm[date] = accmValues
    return accm
}, {});

console.log(result)

Upvotes: 1

Related Questions