All files / src/utils duplicateIndices.ts

0% Statements 0/7
0% Branches 0/2
0% Functions 0/3
0% Lines 0/6

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20                                       
/**
 * 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();
}