I have a list pf products whose data has been split into 3 arrays that holds the name, price, and weight of the product. How do I make a function that finds the duplicate product using hash map?
//Inputs:
name = ["ball", "bat", "glove", "glove", "glove"]
price = [2, 3, 1, 2, 1]
weight = [2, 5, 1, 1, 1]
//Output: true
//Inputs:
name = ["ball", "bat", "glove", "glove", "glove"]
price = [2, 3, 1, 2, 2]
weight = [2, 5, 1, 1, 2]
//Output: false
Javascript doesn't have a HashSet, but there is a Set that'll store anything you like. So, to test for duplicates:
Create an empty Set
Iterate over i = 0..items.length
For every i, create a hash out of name[i], price[i] and weight[i]. Note: it doesn't matter how you do it, as long as the following is true (notice the 3x ===):
hash(name[i], price[i], weight[i]) === hash(name[i], price[i], weight[i])
After creating a hash, check if it already exists in your Set
Reaching the end of the loop without an early return means there are no duplicates
let name, price, weight;
const makeHash = (name, price, weight) =>
`${name}__${price}__${weight}`;
const duplicateTest = () => {
const seen = new Set();
for (let i = 0; i < name.length; i += 1) {
const hash = makeHash(name[i], price[i], weight[i]);
if (seen.has(hash)) return true;
seen.add(hash);
}
return false;
}
name = ["ball", "bat", "glove", "glove", "glove"]
price = [2, 3, 1, 2, 1]
weight = [2, 5, 1, 1, 1]
console.log(duplicateTest()); // Output: true
name = ["ball", "bat", "glove", "glove", "glove"]
price = [2, 3, 1, 2, 2]
weight = [2, 5, 1, 1, 2]
console.log(duplicateTest()); // Output: false
I would firstly challenge the need to split the data into three arrays, then ultimately approach the problem this way if the data structure couldn't be reshaped.
const findDupes = (
[name, ...names],
[price, ...prices],
[weight, ...weights],
res = {},
) => {
const next = ($res) => findDupes(names, prices, weights, $res);
const hash = `${name}\/${price}\/${weight}`;
const dupe = res[hash] ? { name, price, weight } : [];
return [].concat(dupe).concat(
names.length ? next({ ...res, [hash]: true }) : [],
);
};
const name = ["ball", "bat", "glove", "glove", "glove"];
const price = [2, 3, 1, 2, 1];
const weight = [2, 5, 1, 1, 1];
console.log(
findDupes(name, price, weight),
);