'Check if there is a duplicate product between 3 arrays using hash
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
Solution 1:[1]
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),
);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Hitmands |
