20 lines
614 B
TypeScript
20 lines
614 B
TypeScript
/**
|
|
* Find the indices of all elements that occur more than once.
|
|
*
|
|
* @param array The array to search for duplicates.
|
|
* @returns An array of indices where an element occurs more than once, in no particular order.
|
|
*/
|
|
export default function duplicateIndices<T>(array: T[]): number[] {
|
|
const positions = new Map<T, number[]>();
|
|
|
|
array.forEach((value, i) => {
|
|
if (!positions.has(value)) positions.set(value, []);
|
|
positions.get(value)!.push(i);
|
|
});
|
|
|
|
// flatten all index lists with more than one element
|
|
return Array.from(positions.values())
|
|
.filter(idxs => idxs.length > 1)
|
|
.flat();
|
|
}
|