問(wèn)題:數(shù)組對(duì)象去重
var arr = [{name: 'a',id: 1}, {name: 'a',id: 2}, {name: 'b',id: 3}, {name: 'c',id: 4}, {name: 'c',id: 6}, {name: 'b',id: 6}, {name: 'd',id: 7}];
對(duì)數(shù)組對(duì)象name進(jìn)行去重處理, 結(jié)果顯示為:
[{name: 'a',id: 1}, {name: 'b',id: 3}, {name: 'c',id: 4}, {name: 'd',id: 7}];
方法一:es5冒泡排序法娃循,去重arr
var arr = [{name: 'a',id: 1}, {name: 'a',id: 2}, {name: 'b',id: 3}, {name: 'c',id: 4},
{name: 'c',id: 6}, {name: 'b',id: 6}, {name: 'd',id: 7}];
function deWeight() {
for (var i = 0; i < arr.length - 1; i++) {
for (var j = i + 1; j < arr.length; j++) {
if (arr[i].name == arr[j].name) {
arr.splice(j, 1);
//因?yàn)閿?shù)組長(zhǎng)度減小1,所以直接 j++ 會(huì)漏掉一個(gè)元素,所以要 j--
j--;
}
}
}
return arr;
}
var newArr = deWeight();
console.log('%c%s', 'color:red;', '方法一:es5,newArr', newArr);
方法二:es5新建數(shù)據(jù)雙重循環(huán)重绷,去重arr2
var arr2 = [{name: 'a',id: 1}, {name: 'a',id: 2}, {name: 'b',id: 3}, {name: 'c',id: 4},
{name: 'c',id: 6}, {name: 'b',id: 6}, {name: 'd',id: 7}];
var temp = [];
function deWeightTwo() {
arr2.forEach(function(a) {
var check = temp.every(function(b) {
return a.name !== b.name;
})
check ? temp.push(a) : ''
})
return temp;
}
var newArr2 = deWeightTwo();
console.log('%c%s', 'color:red;', '方法二:es5,newArr2', newArr2);
方法三:es6的Map()银酗,去重arr3
var arr3 = [{name: 'a',id: 1}, {name: 'a',id: 2}, {name: 'b',id: 3}, {name: 'c',id: 4},
{name: 'c',id: 6}, {name: 'b',id: 6}, {name: 'd',id: 7}];
let deWeightThree = () => {
let map = new Map();
for (let item of arr3) {
if (!map.has(item.name)) {
map.set(item.name, item);
}
}
return [...map.values()];
}
let newArr3 = deWeightThree();
console.log('%c%s', 'color:red;', '方法三:es6,newArr3', newArr3);
方法四:es5,對(duì)象法去重arr4
var arr4 = [{name: 'a',id: 1}, {name: 'a',id: 2}, {name: 'b',id: 3}, {name: 'c',id: 4},
{name: 'c',id: 6}, {name: 'b',id: 6}, {name: 'd',id: 7}];
// array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
// (function(必選初始值或計(jì)算結(jié)束返回值, 必選當(dāng)前元素, 可選索引, 可選原數(shù)組),可選函數(shù)初始值)
var obj = {};
function deWeightFour() {
arr4 = arr4.reduce(function(a, b) {
obj[b.name] ? '' : obj[b.name] = true && a.push(b);
return a;
}, [])
return arr4;
}
var newArr4 = deWeightFour();
console.log('%c%s', 'color:red;', '方法四:es5,newArr4', newArr4);
原文作者:匆匆那年_海良狈,博客主頁(yè):http://www.reibang.com/u/910c0667c515
95后前端漢子后添,愛(ài)編程、優(yōu)秀薪丁、聰明遇西、理性、沉穩(wěn)严嗜、智慧的程序猿一枚粱檀。