This article describes how to remove duplicate values from JavaScript arrays and strings, and Filter Arrays and strings using various restrictions, if you need a friend, you can refer to the following principle to make the code very clear. Let's look at the code example:
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']
Relatively good Function (not compatible with IE7)
function unique(array){ return array.filter(function(el, index, arr) { return index == arr.indexOf(el); }); }
Better Function (compatible with IE7)
// Remove the duplicate value function getNoRepeat (s) {return s. sort (). join (",,"). replace (/(, | ^) ([^,] +) (, \ 2) + (, | $)/g, "$1 $2 $4 "). replace (/, +/g ,","). replace (/, $ /,""). split (",");} var arr = ["Beijing", "Shanghai", "Tianjin", "Wuhan", "Shanghai", "Tianjin", "Wuhan ", "Beijing", "Shanghai", "Tianjin", "Wuhan ", "Beijing", "Shanghai", "Tianjin", "Wuhan", "Shanghai", "Tianjin", "Wuhan", "Beijing", "Shanghai", "Tianjin ", "Wuhan", "Tianjin", "Wuhan", "Beijing", "Shanghai", "Tianjin ", "Wuhan", "Shanghai", "Tianjin", "Wuhan", "Beijing", "Shanghai", "Tianjin", "Wuhan", "Tianjin", "Wuhan ", "Tianjin", "Wuhan", "Tianjin", "Wuhan"]; arr = getNoRepeat (arr); alert (arr. length); // 4 alert (arr. toString (); // "Beijing", "Shanghai", "Tianjin", "Wuhan"
Map Principle
Var arr = ["Beijing", "Shanghai", "Tianjin", "Wuhan", "Shanghai", "Tianjin", "Wuhan", "Beijing", "Shanghai ", "Tianjin", "Wuhan", "Beijing", "Shanghai ", "Tianjin", "Wuhan", "Shanghai", "Tianjin", "Wuhan", "Beijing", "Shanghai", "Tianjin", "Wuhan", "Tianjin ", "Wuhan", "Tianjin", "Wuhan", "Tianjin", "Wuhan", "Beijing", "Shanghai", "Tianjin", "Wuhan", "Shanghai ", "Tianjin", "Wuhan", "Beijing", "Shanghai", "Tianjin", "Wuhan ", "Tianjin", "Wuhan"]; 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 (); // "Beijing", "Shanghai", "Tianjin", "Wuhan"