'How to remove same date string from object inside an array?

Hello I have a array like this.

const array = [
{date: "2022-02-22 18:00:00"}
{date: "2022-02-22 17:00:00"}
{date: "2022-02-22 18:00:00"}
{date: "2022-02-23 01:00:00"}
{date: "2022-02-23 10:00:00"}
{date: "2022-02-24 18:00:00"}
]

Here I have to keep only one object for each day. Here It should be like that-

[
{date: "2022-02-22 18:00:00"}
{date: "2022-02-23 01:00:00"}
{date: "2022-02-24 18:00:00"}
]

Here you can see 22, 23, 24 date object. Not same date twice. Can anyone help me. I can also use moments js. You I need to use momentjs then please tell me.



Solution 1:[1]

The following should be what you want. Please let me know if this works for you.

const array = [
    {date: "2022-02-22 18:00:00"},
    {date: "2022-02-22 17:00:00"},
    {date: "2022-02-22 18:00:00"},
    {date: "2022-02-23 01:00:00"},
    {date: "2022-02-23 10:00:00"},
    {date: "2022-02-24 18:00:00"}
]

// Slice first 10 characters of array and check for duplicates. Keep first element found.
const unique = array.reduce((acc, curr) => {
    if (acc.length === 0) {
        acc.push(curr)
    } else {
        const found = acc.find(e => e.date.slice(0, 10) === curr.date.slice(0, 10))
        if (!found) {
            acc.push(curr)
        }
    }
    return acc
}, [])

console.log(unique)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1