Last active
June 15, 2022 15:21
-
-
Save specious/bb83fc9c1569d8c035cf2aca3d47c309 to your computer and use it in GitHub Desktop.
Deduplicate an array while constructing an index table to regenerate the original array
This file contains hidden or 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
// | |
// Deduplicates an array and also returns a redundant array containing indices to the original data in the deduplicated array | |
// | |
function dedup(arr) { | |
let indexLookups = [] | |
for (let i = 0; i < arr.length; i++) { | |
let idx = arr.indexOf(arr[i]) | |
// Store a index reference to the first occurrence of the element in the possibly shrinking array that is being deduplicated | |
indexLookups.push(idx) | |
// Remove duplicates from the original array | |
if (idx !== i) | |
arr.splice(i--, 1) | |
} | |
return indexLookups | |
} | |
// | |
// Replace indices with data provided in a second array | |
// | |
function reconstitute(indices, data) { | |
for (let i = 0; i < indices.length; i++) | |
indices[i] = data[indices[i]] | |
} | |
module.exports = { | |
dedup, | |
reconstitute | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment