对于一个元组数组,我将把它们放到一个Map中,让它完成工作。使用此方法时,您必须注意要使用的密钥:
const arrayOfArraysWithDuplicates = [
[1, 'AB'],
[2, 'CD'],
[3, 'EF'],
[1, 'AB'],
[2, 'CD'],
[3, 'EF'],
[3, 'GH'],
]
const uniqueByFirstValue = new Map();
const uniqueBySecondValue = new Map();
arrayOfArraysWithDuplicates.forEach((item) => {
uniqueByFirstValue.set(item[0], item[1]);
uniqueBySecondValue.set(item[1], item[0]);
});
let uniqueList = Array.from( uniqueByFirstValue, ( [ value, name ] ) => ( [value, name] ) );
console.log('Unique by first value:');
console.log(uniqueList);
uniqueList = Array.from( uniqueBySecondValue, ( [ value, name ] ) => ( [value, name] ) );
console.log('Unique by second value:');
console.log(uniqueList);
输出:
Unique by first value:
[ [ 1, 'AB' ], [ 2, 'CD' ], [ 3, 'GH' ] ]
Unique by second value:
[ [ 'AB', 1 ], [ 'CD', 2 ], [ 'EF', 3 ], [ 'GH', 3 ] ]