M
M
mrrangerr2022-02-02 12:46:14
JavaScript
mrrangerr, 2022-02-02 12:46:14

How to group identical objects in an array of objects?

I have an array of objects, how can I group the same objects?
61fa52b2e5f55897616470.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
dollar, 2022-02-02
@dollar

get an array with nested arrays where equivalent objects lie
For example, like this (imperatively):
spoiler
let openHours = {
    monday: {open:"0:00", close:"23:59", breakHours: null},
    friday: {open:"0:00", close:"23:59", breakHours: {from: "14:00", to:"15:00"}},
    sunday: {open:"0:00", close:"23:59", breakHours: {from: "14:00", to:"15:00"}},
}

let temp = {};

for (let day in openHours) {
    let data = openHours[day]
    data.day = day;
    let key = "" + data.open + "-" + data.close + "-"
        + (data.breakHours ? data.breakHours.from+"-"+data.breakHours.to : null)
    if (!temp[key]) temp[key] = [];
    temp[key].push(data);
}

let result = Object.values(temp);
console.log(result);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question