Skip to content

Instantly share code, notes, and snippets.

@techieshark
Created December 12, 2022 10:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save techieshark/04abf9712c242ee7756b20ffd2358e2d to your computer and use it in GitHub Desktop.
Save techieshark/04abf9712c242ee7756b20ffd2358e2d to your computer and use it in GitHub Desktop.
Return a Map of items to their indices in the array #typescript
/**
* Return a Map of items to their indices in the array.
*
* The Map will have an entry for each item in A, with the item as the key and
* an array of indices as the value.
*
* There will be as many items in the Map as there are unique items in `A`.
*
* @param A an array of items of any type `T`
*
*/
function findItemIndices<T>(A: T[]) {
// Create a map to store the indices of each item in A
const itemIndices = new Map<T, number[]>();
A.forEach((item, index) => {
if (!itemIndices.has(item)) {
itemIndices.set(item, [index]);
} else {
itemIndices.get(item).push(index);
}
});
return itemIndices;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment