如何拼接数组 JavaScript 中的重复项
我们有一个包含数字 / 字符串文字的数组,其中包含一些重复的值,我们必须从数组中删除这些值,而不能创建新数组或将重复值存储在任何其他位置。
我们将使用 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 ]
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP