2024.11.23今天我学习了如何获取保留每一个重复数据的最后一条数据,代码如下:
let demo = [
{ name: '苹果', price: 20, time: '07:00:00', id: 1 },
{ name: '苹果', price: 11, time: '19:00:00', id: 1 },
{ name: '苹果', price: 23, time: '09:00:00', id: 1 },
{ name: '香蕉', price: 20, time: '10:00:00', id: 2 },
{ name: '香蕉', price: 12, time: '08:00:00', id: 2 },
{ name: '西瓜', price: 30, time: '07:00:00', id: 3 },
]
let new_demo = [];
demo.forEach((item, index) => {
const data_index = new_demo.findIndex(items => items.id == item.id);
if (data_index !== -1) {
new_demo[data_index] = item;
} else {
new_demo.push(item);
}
})