Reputation: 317
I have the following object:
[
{ createdAt: "08-08-2020, 12:04:19 am", id: "1" },
{ createdAt: "08-08-2020, 12:04:19 am", id: "2" },
{ createdAt: "08-10-2020, 12:04:19 am", id: "3" },
{ createdAt: "08-10-2020, 12:04:19 am", id: "4" },
{ createdAt: "08-12-2020, 12:04:19 am", id: "5" },
{ createdAt: "08-20-2020, 12:04:19 am", id: "6" }
]
As you can see, every array has a creation date and an specific value. What I wanna do here is to create a new object that looks like this:
[
{ createdAt: "08-08-2020", ids: ["1", "2"] },
{ createdAt: "08-10-2020", ids: ["3", "4"] },
{ createdAt: "08-12-2020", ids: ["5"] },
{ createdAt: "08-20-2020", ids: ["6" ]}
]
Basically arranging the ids by date of creation. I've been trying to filter and map this with ECMA6 but the logic it's just not clear to me.
Any help would be greatly appreciated.
Thanks in advance!
Upvotes: 0
Views: 166
Reputation: 89264
This can be accomplished with a basic reduce
operation, grouping elements with the same date using an object.
const arr = [
{ createdAt: "08-08-2020, 12:04:19 am", id: "1" },
{ createdAt: "08-08-2020, 12:04:19 am", id: "2" },
{ createdAt: "08-10-2020, 12:04:19 am", id: "3" },
{ createdAt: "08-10-2020, 12:04:19 am", id: "4" },
{ createdAt: "08-12-2020, 12:04:19 am", id: "5" },
{ createdAt: "08-20-2020, 12:04:19 am", id: "6" }
];
const res = Object.values(
arr.reduce((acc,{createdAt, id})=>{
const date = createdAt.split(",")[0];
acc[date] = acc[date] || {createdAt: date, ids: []};
acc[date].ids.push(id);
return acc;
}, {})
);
console.log(res);
Upvotes: 0
Reputation: 10176
First, create a map between the createdAt and the ids
const array = [
{ createdAt: "08-08-2020, 12:04:19 am", id: "1" },
{ createdAt: "08-08-2020, 12:04:19 am", id: "2" },
{ createdAt: "08-10-2020, 12:04:19 am", id: "3" },
{ createdAt: "08-10-2020, 12:04:19 am", id: "4" },
{ createdAt: "08-12-2020, 12:04:19 am", id: "5" },
{ createdAt: "08-20-2020, 12:04:19 am", id: "6" }
]
const map = {}
array.forEach(item => {
if (map[item.createdAt] === undefined) {
map[item.createdAt] = []
}
map[item.createdAt].push(item.id)
})
Then, rearrange the map into an array:
const resultingArray = Object.entries(map).map(([createdAt, ids]) => ({
createdAt,
ids
}))
Upvotes: 1