巧用reduce、filter過濾陣列中的相同的元素
阿新 • • 發佈:2019-02-09
陣列元素是一個字串:
(function(){
'use strict';
var r,
arr = ['apple', 'strawberry', 'banana', 'pear', 'apple', 'orange', 'orange', 'strawberry'];
r = arr.filter(function (element, index, self) {
return self.indexOf(element) === index;
});
console.log(r)
})()
陣列元素是一個對像:
(function(){ 'use strict'; var arr = [ {name:"lili"}, {name:"liwang"}, {name:"liliu"}, {name:"lee"}, {name:"lili"}, {name:"awmgli"}, {name:"awmg"}, {name:"ggmg"}, {name:"awmgli"} ]; var obj = {}; arr = arr.reduce(function(a, b) { obj[b.name] ? '' : obj[b.name] = true && a.push(b); return a }, []) console.log(arr) })()