请问这种数组怎么操作

WEB菜鸟
  • 270

37751619755430_.pic_hd.jpg
【0,1,2,3,4,5】,4和0 id相同我需要4替换0并删除4,【0,1,2,3,4】,5变为4

回复
阅读 249
2 个回答
const temp = [
  {
    id: 0,
    value: 1
  },
  {
    id: 1,
    value: 2
  },
  {
    id: 2,
    value: 3
  },
  {
    id: 0,
    value: 4
  },
  {
    id: 4,
    value: 5
  }
];

const deleteDuplicate = (arr) => {
  const idToIndexMap = new Map();
  const ans = [];
  const swap = (i, j, arr) => {
    const temp = arr[i];
    arr[i] = arr[j];
    arr[j] = temp;
  };

  for (let i = 0; i < arr.length; ++i) {
    if (!idToIndexMap.has(arr[i].id)) {
      ans.push(arr[i]);
      idToIndexMap.set(arr[i].id, ans.length - 1);
    } else {
      const duplicateIdIndex = idToIndexMap.get(arr[i].id);
      ans.push(arr[i]);
      swap(ans.length - 1, duplicateIdIndex, ans);
      ans.pop();
    }
  }

  return ans;
};

console.log(deleteDuplicate(temp));


for(let i = 0; i < arr.length; i++){
    let index = arr.findIndex(item => item.id === arr[i].id)
    if(index < i){
        arr.splice(index, 1, arr[i])
        arr.splice(i--, 1)
    }
}
你知道吗?

宣传栏