Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lodash: create new array with latest items

I have an array as below

[{
        "id": "001",
        "name": "A",
        "timestamp_created": "2019-02-27T11:22:19"
    },
    {
        "id": "002",
        "name": "A",
        "timestamp_created": "2019-02-27T11:30:19"
    },
    {
        "id": "003",
        "name": "B",
        "timestamp_created": "2019-02-27T10:15:19"
    },
    {
        "id": "004",
        "name": "B",
        "timestamp_created": "2019-02-27T11:05:19"
    }
]

I want to create a new array based on the above array, but with only latest item, (group by name of item).

 [{
            "id": "002",
            "name": "A",
            "timestamp_created": "2019-02-27T11:30:19"
        },
        {
            "id": "004",
            "name": "B",
            "timestamp_created": "2019-02-27T11:05:19"
        }
    ]

How to combine different Lodash's features to achieve the result?

Any suggestion, please help me.

like image 751
Phong Vu Avatar asked Aug 12 '26 17:08

Phong Vu


1 Answers

You could take Map, collect all latest items (by checking timestamp_created), grouped by name and get the values.

var data = [{ id: "002", name: "A", timestamp_created: "2019-02-27T11:30:19" }, { id: "003", name: "B", timestamp_created: "2019-02-27T10:15:19" }, { id: "004", name: "B", timestamp_created: "2019-02-27T11:05:19" }, { id: "001", name: "A", timestamp_created: "2019-02-27T11:22:19" }],
    result = Array.from(data
        .reduce(
            (m, o) => m.has(o.name) && m.get(o.name).timestamp_created > o.timestamp_created
               ? m
               : m.set(o.name, o),
            new Map
        )
        .values()
    );
    
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
like image 199
Nina Scholz Avatar answered Aug 14 '26 11:08

Nina Scholz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!