Last active
October 29, 2020 23:22
-
-
Save lisavogtsf/a4469e8995cf4ba8b4ea3d174e746c39 to your computer and use it in GitHub Desktop.
dedupe furniture array
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
// furniture.js -- run in terminal containing file using: node furniture.js | |
// dedupe objects | |
// lisavogt.sf@gmail.com | |
// deduplicate an array of objects by checking for unique nested properties | |
function dedupeObjects(inputArray) { | |
let dedupedArray = []; | |
let referenceLib = {}; | |
for (let item of inputArray) { // O(n) -- items in original list | |
// for first appearance of an item name, add it as an array to a new hash map key | |
if (!referenceLib[item.name]) { | |
referenceLib[item.name] = [item]; | |
} else { | |
// for subsequent appearance, check more closely | |
const list = referenceLib[item.name]; | |
// need to examine each item in the array with matching item.name | |
for (let listItem of list) { // O(m) -- length of longest array in hash map | |
// check for uniqueness in nested properties | |
if (item.details.marker !== listItem.details.marker) { | |
referenceLib[item.name].push(item); | |
} | |
} | |
} | |
} | |
// flatten deduped lists from object to array | |
for (const namedList of Object.values(referenceLib)) { // O(k) -- number of unique names | |
dedupedArray = dedupedArray.concat(namedList); | |
} | |
// O(nm + k) | |
// worst case resolves down to O(n^2), effectively less since m and k are both less than n | |
// and m and k are inversely proportional | |
// best case O(n) where there is no duplication, never even enter the else, k is 1 [edit k is n, but O(2n) is O(n)] | |
return dedupedArray; | |
} | |
const stock = [ | |
{ | |
name: 'chair', | |
inventory: 5, | |
price: 24.99, | |
details: { | |
units: 3, | |
marker: '123a' | |
} | |
},{ | |
name: 'chair', | |
inventory: 5, | |
price: 24.99, | |
details: { | |
units: 3, | |
marker: '123a' | |
} | |
}, | |
{ | |
name: 'chair', | |
inventory: 5, | |
price: 24.99, | |
details: { | |
units: 4, | |
marker: '123b' | |
} | |
}, | |
{ | |
name: 'table', | |
inventory: 2, | |
price: 2.99, | |
details: { | |
units: 3, | |
marker: '124a' | |
} | |
}, | |
{ | |
name: 'sofa', | |
inventory: 1, | |
price: 243.99, | |
details: { | |
units: 2, | |
marker: '126a' | |
} | |
}, | |
]; | |
console.log(dedupeObjects(stock)); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment