JavaScript 数组去重 ES6 方法
方法一
new Set()生成出来的数据是Set数据结构,需要自行转换成对应结构
javascript
let array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 2, 3, 3, 3, 9, 8, 9, 's', 'o', 'o'];
Array.from(new Set(array));
方法二
javascript
let array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 2, 3, 3, 3, 9, 8, 9, 's', 'o', 'o'];
...new Set(array);
或
const a = '12345678971100';
const b = [...new Set(a)].join('');
方法三
使用indexOf() 方法用于在字符串中查找指定子串,并返回第一个匹配项的索引。
javascript
let array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 2, 3, 3, 3, 9, 8, 9, 's', 'o', 'o'];
let newarr = [];
for (var i = 0; i < array.length; i++) {
if (newarr.indexOf(array[i]) == -1) {
newarr.push(array[i]);
};
};
方法四
javascript
let array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 2, 3, 3, 3, 9, 8, 9, 's', 'o', 'o'];
let newarr2 = [];
array.sort(); //先将数组排序
for (var i = 0; i < array.length; i++) {
if (array[i] !== array[i + 1]) { //判断后一项 是否跟前一项一样 将后一项放入新数组
newarr2.push(array[i]);
};
};
方法五
javascript
let array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 2, 3, 3, 3, 9, 8, 9, 's', 'o', 'o'];
var res = [array[0]];
for (var i = 0; i < array.length; i++) {
var repeat = false;
for (var j = 0; j < res.length; j++) {
if (array[i] == res[j]) {
repeat = true;
break;
}
}
if (!repeat) {
res.push(array[i]);
}
}
方法六
javascript
let array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 2, 3, 3, 3, 9, 8, 9, 's', 'o', 'o'];
var res = [];
var json = {};
for (var i = 0; i < array.length; i++) {
if (!json[array[i]]) {
res.push(array[i]);
json[array[i]] = 1;
}
}