概要
TypeScript にて Id を持つようなオブジェクトの配列に対して重複を排除する方法のメモです。
配列要素において、順番が先のオブジェクトが優先的に採用されます。
コードサンプル
// 対象となるオブジェクト
class Sample {
constructor(public id: number, public name: string) { }
}
// 重複排除の処理
const distinct = (samples: Sample[]) => {
return samples.filter((x, i, arr) => arr.findIndex(y => y.id === x.id) === i);
}
// サンプル実装
const samples = [
new Sample(1, 'Tanaka'),
new Sample(2, 'Yamada'),
new Sample(3, 'Suzuki'),
new Sample(4, 'Sato'),
new Sample(5, 'Nakamura'),
new Sample(2, 'Two'),
new Sample(3, 'Three')
];
const distincted = distinct(samples);
distincted.forEach(x => console.log(x.id + ":" + x.name));
// 1:Tanaka
// 2:Yamada
// 3:Suzuki
// 4:Sato
// 5:Nakamura
const samples2 = [
new Sample(2, 'Yamada'),
new Sample(6, 'Ito'),
];
// 応用技で複数のオブジェクト配列を合成するパターン
const distincted2 = distinct([...samples, ...samples2]);
distincted2.forEach(x => console.log(x.id + ":" + x.name));
// 1:Tanaka
// 2:Yamada
// 3:Suzuki
// 4:Sato
// 5:Nakamura
// 6:Ito