如果追求性能,可以采用空間換時間的做法,在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>