Tengo una lista de productos cuyos datos se han dividido en 3 matrices que contienen el nombre, el precio y el peso del producto. ¿Cómo hago una función que encuentre el producto duplicado usando el mapa hash?
//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: falseJavascript no tiene un HashSet , pero hay un Set que almacenará todo lo que quieras. Entonces, para probar si hay duplicados:
Crear un Set vacío
Iterar sobre i = 0..items.length
Para cada i , cree un hash a partir de name[i] , price[i] y weight[i] . Nota: no importa cómo lo haga, siempre que lo siguiente sea cierto (observe el 3x === ):
hash(name[i], price[i], weight[i]) === hash(name[i], price[i], weight[i])
Después de crear un hash, verifique si ya existe en su Set
Llegar al final del bucle sin un retorno anticipado significa que no hay duplicados
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: falseEn primer lugar, desafiaría la necesidad de dividir los datos en tres matrices y, en última instancia, abordaría el problema de esta manera si la estructura de datos no pudiera modificarse.
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), );