两个数组除去id相同的
const arr1 = [
{id:1,name:'a'},
{id:2,name:'abc'},
{id:3,name:'abbb'},
{id:4,name:'abxxx'},
{id:5,name:'xyz'},
{id:6,name:'abcdef'},
{id:7,name:'abzzzz'}
];
const arr2 = [
{id:1,name:'a'},
{id:5,name:'xyz'},
{id:7,name:'abzzzz'}
];
let result = arr1.filter(item1 => arr2.every(item2 => item2.id !== item1.id))
console.log(result)
image.png输出结果
单个数组去重,形成新的数组
方法1
let array = [1, 1, 1, 1, 2, 3, 4, 4, 5, 3, undefined, undefined, null, null, Object, Object];
let set = Array.from(new Set(array));
console.log(set);
输出结果
image.png方法2
let arr = [1, 2, 2, 3, 4, 5, 5, 6, 7, 7, 8, 8, 0, 8, 6, 3, 4, 56, 2, undefined, undefined, null, null, Object, Object];
let arr2 = arr.filter((x, index, self) => self.indexOf(x) === index)
console.log(arr2)
输出结果
image.png数组内去除相同id的对象
方法1:
let person = [
{id: 0, name: "小明"},
{id: 1, name: "小张"},
{id: 2, name: "小李"},
{id: 3, name: "小孙"},
{id: 1, name: "小周"},
{id: 2, name: "小陈"},
];
let obj = {};
let arr = person.reduce((cur,next) => {
obj[next.id] ? "" : obj[next.id] = true && cur.push(next);
return cur;
},[]) //设置cur默认类型为数组,并且初始值为空的数组
console.log(arr);
输出结果
image.png方法2:
let person = [
{id: 0, name: "小明", testId: 1},
{id: 1, name: "小张", testId: 2},
{id: 2, name: "小李", testId: 3},
{id: 3, name: "小孙", testId: 4},
{id: 1, name: "小周", testId: 1},
{id: 2, name: "小陈", testId: 1},
];
function filterSameIndex(arr, index) {
// arr是数组,index是要过滤的目标
let array = arr
array.forEach(c => {
const res = arr.filter(i => i[index] !== c[index])
arr = [...res, c]
})
console.log(arr)
return arr
}
filterSameIndex(person, 'testId')
输出结果
image.png
两个数组合并,有相同键的替换,不同则添加
let arr = [
{ key: 1, name: '1-1' },
{ key: 2, name: '1-2' },
{ key: 3, name: '1-3' },
{ key: 4, name: '1-4' },
]
let arr1 = [
{ key: 1, name: '2-1' },
{ key: 3, name: '2-3' },
{ key: 5, name: '2-5' },
]
let arr2 = []
let obj = {};
arr2 = [...arr, ...arr1].reduce((cur, next) => {
if (obj[next.key]) {
let index = cur.findIndex(item => item.key === obj[next.key])
cur.splice(index, 1, next)
} else {
// 因为对象是储存的键值对,
// 所以对象obj的键arr[i]必须对应一个值,这个值是什么不重要,但别是undefined,因为这样你就不容易判断对象里面有没有这个键。
obj[next.key] = next.name && cur.push(next)
}
return cur;
}, []) //设置cur默认类型为数组,并且初始值为空的数组
console.log('arr2', arr2)
输出结果:
image.png
网友评论