admin管理员组

文章数量:1410689

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 bine different Lodash's features to achieve the result?

Any suggestion, please help me.

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 bine different Lodash's features to achieve the result?

Any suggestion, please help me.

Share Improve this question edited Feb 28, 2019 at 9:15 Chamila Maddumage 3,8862 gold badges34 silver badges44 bronze badges asked Feb 27, 2019 at 15:19 Phong VuPhong Vu 2,8966 gold badges27 silver badges53 bronze badges 2
  • Latest two items? Latest item of each name What? – mplungjan Commented Feb 27, 2019 at 15:21
  • As example, array has 2 items (A,B) but different timestamp created, I wanna create a new array with latest A and latest B, depend on timestamp – Phong Vu Commented Feb 27, 2019 at 15:24
Add a ment  | 

5 Answers 5

Reset to default 2

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; }

Without using the library lodash, you can generate the result using Array.reduce():

const input = [
    {
        "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"
    }
];

let res = input.reduce((acc, {id, name, timestamp_created}) =>
{
    acc[name] = acc[name] || {id, name, timestamp_created};
    
    if (acc[name].timestamp_created < timestamp_created)
        acc[name] = {id, name, timestamp_created};    

    return acc;
}, {});

console.log(Object.values(res));
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}

Great answers so far. As OP asked for a Lodash solution, here's that:

const data = [{
    "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"
}
];

const reduceFunction = (acc, val) => {
    if (val.name in acc) {
        if (val.timestamp_created > acc[val.name].timestamp_created) {
            acc[val.name] = val
        }
    } else {
        acc[val.name] = val
    }

    return acc;
};

const filteredData = _.values(
    _.reduce(data, reduceFunction, {})
);

If you want to use lodash this will do the job.

function latestItems(original) {
    filtered = [];
    grouped = _.groupBy(original, "name");
    _.forEach(grouped, function (group) {
        newest = {
            "timestamp_created": "0"
        };
        _.forEach(group, function (item) {
            if (item.timestamp_created > newest.timestamp_created) {
                newest = item;
            }
        });
        filtered.push(newest);
    });

    return filtered;
}

Short solution using lodash

const data = [...]
const result = _(data)
  .groupBy('name')
  .map(group => _.maxBy(group, 'timestamp_created'))
  .value()

Use groupBy to group by name. Then use maxBy to get object that has max timestamp_created.

_.maxBy(array, [iteratee=_.identity])

This method is like _.max except that it accepts iteratee which is invoked for each element in array to generate the criterion by which the value is ranked. The iteratee is invoked with one argument: (value).

https://lodash./docs/4.17.11#maxBy

本文标签: javascriptLodash create new array with latest itemsStack Overflow