Created
December 12, 2022 10:02
-
-
Save techieshark/04abf9712c242ee7756b20ffd2358e2d to your computer and use it in GitHub Desktop.
Return a Map of items to their indices in the array #typescript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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