0

Hi I have an array of objects such as this:

const data = [ {day: "Monday", to: "12.00", from: "15.00"}, {day: "Monday", to: "18.00", from: "22.00"}, {day: "Tuesday", to: "12.00", from: "22.00"}]

I need to make a new array from this existing one and have it like below. I know I need to use .map method to create a new array, but my knowledge beyond this is lacking. Really appreciate it if someone could guide me in the right direction please.

Example of new array I want:

const newArr = [{"Monday":[{"12.00", "15.00"}, {"18.00", "22.00"}], {"Tuesday": ["9.00", "5.00"]}]

1 Answers1

0

Using Array#reduce to iterate over your array and accumulte the desired data. Look for every day if there exists in the accumulted dresult-object an property with this day as keyname. If not then create it with an object with again the day as property and an empty array . In all cases add to this array your times.
At last use Object#values to get the values out of it.

const data = [ {day: "Monday", to: "12.00", from: "15.00"}, {day: "Monday", to: "18.00", from: "22.00"}, {day: "Tuesday", to: "12.00", from: "22.00"}];

let res = Object.values(data.reduce((acc, cur) => {
    if (!acc[cur.day]) {
        acc[cur.day] = {[cur.day]: []};
    }
    acc[cur.day][cur.day].push([cur.to, cur.from]);
    return acc;
}, {}));


console.log(res);
Sascha
  • 4,576
  • 3
  • 13
  • 34