Home >Web Front-end >JS Tutorial >Detailed explanation of how to remove duplicate values ​​from JavaScript arrays and strings_javascript skills

Detailed explanation of how to remove duplicate values ​​from JavaScript arrays and strings_javascript skills

WBOY
WBOYOriginal
2016-05-16 15:11:351857browse

原理在代码中表现得非常清晰,我们直接来看代码例子:

var ages = array.map(function(obj) { return obj.age; }); 
ages = ages.filter(function(v,i) { return ages.indexOf(v) == i; }); 
 
console.log(ages); //=> [17, 35] 
function isBigEnough(element) { 
 return element >= 10; 
} 
var filtered = [12, 5, 8, 130, 44].filter(isBigEnough); 
// filtered is [12, 130, 44] 

function onlyUnique(value, index, self) {  
  return self.indexOf(value) === index; 
} 
 
// usage example: 
var a = ['a', 1, 'a', 2, '1']; 
var unique = a.filter( onlyUnique ); // returns ['a', 1, 2, '1'] 

比较好使的Function(不兼容IE7)

function unique(array){ 
  return array.filter(function(el, index, arr) { 
    return index == arr.indexOf(el); 
  }); 
} 

 
比较好使的Function(兼容IE7)

//去除数组中重复值 
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()); // "北京", "上海", "天津", "武汉" 

利用map原理

var arr = ["北京", "上海", "天津", "武汉", "上海", "天津", "武汉", "北京", "上海", "天津", "武汉", "天津", "武汉", "天津", "武汉", "天津", "武汉", 
"北京", "上海", "天津", "武汉", "上海", "天津", "武汉", "北京", "上海", "天津", "武汉", "天津", "武汉", "天津", "武汉", "天津", "武汉", 
"北京", "上海", "天津", "武汉", "上海", "天津", "武汉", "北京", "上海", "天津", "武汉", "天津", "武汉", "天津", "武汉", "天津", "武汉"]; 
 
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()); 
// "北京", "上海", "天津", "武汉" 

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn