1、数组去重
let value = [1,2,1,3,6,6,1,3,1,2,8]
let set = new Set();
value.forEach(item => {
set.add(item)
})
let a = Array.from(set);
console.log(a)
// es6:
let newValue = [...new Set(value)]
console.log(newValue)
2、两个a, b数组对比,a数组是b数组的一部分id的集合,想要获取a数组的项(项都为id)对应b数组中的id中的name属性的值的新数组c!简单说: 获取一个新数组c,新数组c的项跟a数组的项是在b数组中同一项的
let value = [{id: 1, name: 'jack'}, {id: 2, name: 'nora'}, {id: 3, name: 'adien'}, {id: 4, name: 'rose'}];
let ids = [2, 4];
let names = [];
let obj = {};
ids.forEach(item=> {
obj[item] = item // 属性与值相同
});
console.log(obj) // {2: 2, 4: 4}
value.forEach(item => {
if(obj[item.id]){ // 通过判断a数组是否有这个属性得到b数组的项
names.push(item.name) // 添加到新数组c
}
})
console.log(names)
3、另一种方法,循环嵌套,两个数组循环,对比判断
let value = [{id: 1, name: 'jack'}, {id: 2, name: 'nora'}, {id: 3, name: 'adien'}, {id: 4, name: 'rose'}];
let ids = [2, 4];
let names = [];
value.forEach(item => {
ids.forEach(i => {
if(item.id === i) { // a数组的项与b数组的项里的id比较
names.push(item.name)
}
})
})
console.log(names)
给生活加点甜