數組對象去重
- 方法1:利用對象訪問屬性的方法,判斷對象中是否存在key、value
const arr = [
{
key: "1",
value: "西瓜"
},
{
key: "1",
value: "蘋果"
},
{
key: "3",
value: "桃子"
}
];
const list = [
{
key: "1",
value: "哈密瓜"
},
{
key: "2",
value: "黃瓜"
},
{
key: "3",
value: "黃瓜"
}
];
function unique (obj1,obj2,targe) {
const data = []; // 建立一個新數組
const obj = {}; // 建立一個新對象
const list = obj1.concat(obj2);
for (let i=0; i< list.length; i++) {
if (!obj[list[i][targe]]) { // 判斷對象不存在key、value
data.push(list[i]);
obj[list[i][targe]] = true;
}
}
return data;
}
console.log( unique(arr, list, "value"));
複製代碼
- 方法2:利用reduce方法遍歷數組,reduce第一個參數是遍歷須要執行的函數,第二個參數是item的初始值
const arr = [
{
key: "1",
value: "西瓜"
},
{
key: "1",
value: "蘋果"
},
{
key: "3",
value: "桃子"
}
];
const list = [
{
key: "1",
value: "哈密瓜"
},
{
key: "2",
value: "黃瓜"
},
{
key: "3",
value: "黃瓜"
}
];
function unique (obj1,obj2,targe) {
const obj = {}; // 建立一個新對象
const list = obj1.concat(obj2);
const data = list.reduce(function(item,next) {
if (!obj[next[targe]]) {
item.push(next)
obj[next[targe]] = true;
}
return item;
}, []);
return data;
}
console.log(unique(arr, list, "value"));
複製代碼
const arr = [
{
key: "1",
value: "西瓜"
},
{
key: "1",
value: "蘋果"
},
{
key: "3",
value: "桃子"
}
];
const list = [
{
key: "1",
value: "哈密瓜"
},
{
key: "2",
value: "黃瓜"
},
{
key: "3",
value: "黃瓜"
}
];
function unique(obj1,obj2,targe) {
const data = [...obj1, ...obj2];
const res = new Map();
return data.filter((value) => {
return !res.has(value[targe]) && res.set(value[targe], 1)
} )
}
console.log(unique(arr, list, "value"));
複製代碼