0

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?

1
  • any other efficient ways is okay too I couldn't figure out which one is the best way to store them since the data depends on dates and their times Commented Oct 15, 2020 at 10:21

2 Answers 2

1
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)
Sign up to request clarification or add additional context in comments.

Comments

0

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

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.