如何在数组JavaScript中拼接重复项

我们有一个包含一些重复值的Number / String文字数组,我们必须从数组中删除这些值,而无需创建新数组或将重复值存储在其他任何地方。

我们将使用Array.prototype.splice()方法来就地删除条目,并且将利用Array.prototype.indexOf()和Array.prototype.lastIndexOf()方法来确定任何元素的重复性。

示例

const arr = [1, 4, 6, 1, 2, 5, 2, 1, 6, 8, 7, 5];
arr.forEach((el, ind, array) => {
   if(array.indexOf(el) !== array.lastIndexOf(el)){
      array.splice(ind, 1);
   }
});
console.log(arr);

输出结果

控制台中的输出将为-

[
   4, 1, 5, 2,
   6, 8, 7
]