假设我有一个这样的结构…
let data = [
{ id: "Ik6e" },
{ id: "H0uD" },
{ id: "E^di" },
{ id: "Ik6e" },
{ id: "Ik6e" },
];
我想删除一个id
为Ik6e
的对象的实例(不管是哪一个(。我想要一个新的data
值是…
[
{ id: "Ik6e" },
{ id: "H0uD" },
{ id: "E^di" },
{ id: "Ik6e" },
]
既然我的项目使用了Lodash,那么使用Lodash是否有可能实现这一点?如果不是,香草JS就可以了。
您可以使用filter
来创建一个新数组。对从1开始的每个id保持倒计数,并在其倒计数值为0时排除该id(falsy(。这将始终排除同一id的第二次出现。
let data = [{ id: "Ik6e" }, { id: "H0uD" },{ id: "E^di" },{ id: "Ik6e" },{ id: "Ik6e" }];
let count = {};
let result = data.filter(({id}) => count[id] = (count[id]??2) - 1);
console.log(result);
我确信一定有一个更简单/更线性的解决方案,但这应该有效:
const data = [
{ id: "Ik6e" },
{ id: "H0uD" },
{ id: "E^di" },
{ id: "Ik6e" },
{ id: "Ik6e" },
];
function removeLastDuplicate(arr) {
// 1. create an object to store all indexes of items with the same ID
const itemIdIndexes = arr.reduce((acc, item, index) => {
if (Object.keys(acc).indexOf(item.id) === -1) {
acc = {
...acc,
[item.id]: [index]
};
} else {
acc[item.id].push(index);
}
return acc
}, {});
// 2. find the indexes of the items to be deleted
const indexesToDelete = Object.values(itemIdIndexes)
.filter(item => item.length > 1) // filter only duplicated IDs
.map(item => item[item.length - 1]) // store the last index of duplicated IDs
// 3. return a copy of the original array, with the last occurrence of duplicated items deleted
return arr.filter((item, index) => indexesToDelete.indexOf(index) === -1);
}
const dataModified = removeLastDuplicate(data)
console.log('data:', data);
console.log('dataModified:', dataModified);
如果你喜欢删除第一个而不是最后一个,你可以替换:
// 2. find the indexes of the items to be deleted
const indexesToDelete = Object.values(itemIdIndexes)
.filter(item => item.length > 1) // filter only duplicated IDs
.map(item => item[item.length - 1])
带有:
// 2. find the indexes of the items to be deleted
const indexesToDelete = Object.values(itemIdIndexes)
.filter(item => item.length > 1) // filter only duplicated IDs
.map(item => item[0])
试试这个:
const removeOneItem = (list, target) => {
const targetIndex = list.findIndex(item => item.id === target);
list.splice(targetIndex, 1)
}
removeOneItem(data, 'Ik6e');
试试这个:
let data = [
{ id: "Ik6e" },
{ id: "H0uD" },
{ id: "E^di" },
{ id: "Ik6e" },
{ id: "Ik6e" },
];
let newData = []
data.forEach(ele=>{
if(newData.indexOf(ele.id) === -1){
newData.push(ele)
}
})
console.log(newData)
让我知道它是否有效