JavaScript 实现数组去重
演示Demo 数组去重
// 方法一
function unique1(a) {
var res = [];
for (var i = 0, len = a.length; i < len; i++) {
for (var j = i + 1; j < len; j++) {
// 这一步十分巧妙
// 如果发现相同元素
// 则 i 自增进入下一个循环比较
if (a[i] === a[j])
j = ++i;
}
res.push(a[i]);
}
return res;
}
var a = [1, 1, '1', '2', 1];
console.log('去重前: ' + a);
var ans = unique1(a);
console.log('去重后: ' + ans); // => ["1", "2", 1]
// 方法二
function unique2(a) {
var res = [];
for (var i = 0, len = a.length; i < len; i++) {
var item = a[i];
for (var j = 0, jLen = res.length; j < jLen; j++) {
if (res[j] === item)
break;
}
if (j === jLen)
res.push(item);
}
return res;
}
var a = [1, 1, '1', '2', 1];
console.log('去重前: ' + a);
var ans = unique2(a);
console.log('去重后: ' + ans); // => [1, "1", "2"]
// 方法三
function unique3(names) {
var uniqueNames = [];
$.each(names, function(i, el) {
if ($.inArray(el, uniqueNames) === -1)
uniqueNames.push(el);
});
return uniqueNames;
}
var names = ["Mike", "Matt", "Nancy", "Adam", "Jenny", "Nancy", "Carl"];
console.log('去重前: ' + names);
var uniqueNames = unique3(names);
console.log('去重后: ' + uniqueNames);
参考资料