Skip to content

Instantly share code, notes, and snippets.

@specious
Last active June 15, 2022 15:21
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 specious/bb83fc9c1569d8c035cf2aca3d47c309 to your computer and use it in GitHub Desktop.
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
//
// 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