前端之家收集整理的这篇文章主要介绍了
详解JavaScript数组和字符串中去除重复值的方法,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
原理在代码中表现得非常清晰,我们直接来看代码例子:
console.log(ages); //=> [17,35]
@H_
403_3@
= 10;
}
var filtered = [12,5,8,130,44].filter(isBigEnough);
// filtered is [12,44]
@H_403_3@
// usage example:
var a = ['a',1,'a',2,'1'];
var unique = a.filter( onlyUnique ); // returns ['a','1']
@H_403_3@
去除数组中重复值
function getNoRepeat(s) {
return s.sort().join(",").replace(/(,|^)([^,]+)(,\2)+(,|$)/g,"$1$2$4").replace(/,+/g,",").replace(/,$/,"").split(",");
}
var arr = ["北京","上海","天津","武汉","北京","武汉"];
arr = getNoRepeat(arr);
alert(arr.length);// 4
alert(arr.toString()); // "北京","武汉"
@H_403_3@
var json = {};
for(var i = 0; i < arr.length; i++){
json[arr[i]] = arr[i];
}
arr = new Array();
for(var key in json){
arr.push(key);
}
alert(arr.toString());
// "北京","武汉" @H_403_3@