Home > Web Front-end > JS Tutorial > body text

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

WBOY
Release: 2016-05-16 15:11:35
Original
1788 people have browsed it

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

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] 
Copy after login
function isBigEnough(element) { 
 return element >= 10; 
} 
var filtered = [12, 5, 8, 130, 44].filter(isBigEnough); 
// filtered is [12, 130, 44] 

Copy after login
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'] 
Copy after login

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

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


比较好使的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()); // "北京", "上海", "天津", "武汉" 
Copy after login

利用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()); 
// "北京", "上海", "天津", "武汉" 
Copy after login

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!