js 算法 两个数组比较去重,性能优化
如果追求性能,可以采用空间换时间的做法,在JS中最常见的处理方式就是构建Object,因为Object查找key的时间复杂度是O(1),而数组是O(n)
<!DOCTYPE html> <html> <head> <title>js两个数组比较去重</title> </head> <body> <script type="text/javascript"> // 如果追求性能,可以采用空间换时间的做法,在JS中最常见的处理方式就是构建Object,因为Object查找key的时间复杂度是O(1),而数组是O(n) const list1 = [ {id: 0, name: 'xiaomin'}, {id: 1, name: 'xiaohong'}, ]; const list2 = [ {id: 0, name: 'xiaomin'}, {id: 1, name: 'xiaohong'}, {id: 3, name: 'xiaomin'}, {id: 4, name: 'xiaohong'}, ]; // 首先构造Object const idSet = list1.reduce((acc, v) => { acc[v.id] = true; return acc; }, {}); console.log('构造Object', idSet) // 遍历list2,去掉在idSet中存在的id const result = list2.filter(v => !idSet[v.id]); const repeat = list2.filter(v => idSet[v.id]); console.log('去重后的result', result) console.log('重复的repeat', repeat) </script> </body> </html>
打印结果:
<!DOCTYPE html>
<html>
<head>
<title>js两个数组比较去重</title>
</head>
<body>
<script type="text/javascript">
// 如果追求性能,可以采用空间换时间的做法,在JS中最常见的处理方式就是构建Object,因为Object查找key的时间复杂度是O(1),而数组是O(n)
const list1 = [
{id: 0, name: 'xiaomin'},
{id: 1, name: 'xiaohong'},
];
const list2 = [
{id: 0, name: 'xiaomin'},
{id: 1, name: 'xiaohong'},
{id: 3, name: 'xiaomin'},
{id: 4, name: 'xiaohong'},
];
// 首先构造Object
const idSet = list1.reduce((acc, v) => {
acc[v.id] = true;
return acc;
}, {});
console.log('构造Object', idSet)
// 遍历list2,去掉在idSet中存在的id
const result = list2.filter(v => !idSet[v.id]);
const repeat = list2.filter(v => idSet[v.id]);
console.log('去重后的result', result)
console.log('重复的repeat', repeat)
</script>
</body>
</html>