在 JavaScript 内的数组中删除对象重复项的单个实例

Remove a single instance of object dulplicates in an array inside JavaScript

假设我有这样的结构...

let data = [
  { id: "Ik6e" },
  { id: "H0uD" },
  { id: "E^di" },
  { id: "Ik6e" },
  { id: "Ik6e" },
];

并且我想删除具有 Ik6eid 对象的一个​​实例(无论是哪一个)。 我想要一个新的 data 值是...

[
  { id: "Ik6e" },
  { id: "H0uD" },
  { id: "E^di" },
  { id: "Ik6e" },
]

由于我的项目使用了 Lodash,是否可以使用 Lodash 实现这一目标?如果没有,vanilla JS 就好了。

试试这个:

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)

如果有效请告诉我

您可以使用 filter so 创建一个新数组。对每个从 1 开始的 id 进行倒计时,并在其倒计时值为 0(falsy)时排除该 id。这将始终踢出 second 出现的相同 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 removeOneItem = (list, target) => {
  const targetIndex = list.findIndex(item => item.id === target);
  list.splice(targetIndex, 1)
}
  
removeOneItem(data, 'Ik6e');

我很确定一定有更简单/更线性的解决方案,但这应该可行:

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])