首页 > 解决方案 > 如何在列表中搜索重复项(javascript)?

问题描述

我尝试在数组中查找重复项并得到一个错误,我很高兴为这个问题提供任何解决方案附件是代码:

let names = itemList[0].getElementsByTagName("span")[0].innerText;
for (i = 1; i < itemList.length; i++) {
  if (!(itemList[i].getElementsByTagName("span")[0].innerText in names)) {
    names.push(itemList[i].getElementsByTagName("span")[0].innerText);
  }
}

标签: javascript

解决方案


You can use indexOf. If the indexOf that item in the array you're trying to push to is -1, that means it doesn't exist, and that you can go ahead and push it in. Otherwise, do nothing. You can also reverse this, and add to the array from the other if it already exists, and do nothing if it doesn't.

Example:

const array = [1, 2, 3, 4, 5, 6, 7, 8];

// We are adding this. Expecting to not add the numbers that are already there
const toPushTo = [1, 10, 5];

const addToArrayIfNotDuplicate = (arr)=> {
  arr.forEach(item=>{
    toPushTo.indexOf(item) === -1 ? toPushTo.push(item) : null;
  })
};

addToArrayIfNotDuplicate(array);
console.log(toPushTo);


推荐阅读