Necesito verificar si una matriz contiene todos los elementos de otra matriz, incluidos los mismos duplicados. La segunda matriz puede tener elementos adicionales. Estoy usando cada... incluye, pero no se da cuenta de que la segunda matriz no tiene los duplicados correctos.
Por ejemplo:
const arr1 = [1, 2, 2, 3, 5, 5, 6, 6] const arr2 = [1, 2, 3, 5, 6, 7] if(arr1.every(elem => arr2.includes(elem))){ return true // should return false because arr2 does not have the same duplicates }¡Gracias!
Editar: arr1 es una de las muchas matrices que estoy recorriendo y que provienen de un algoritmo de recorrido de gráfico, por lo que me gustaría evitar reestructurarlas en un objeto para crear una estructura de datos de diccionario si es posible.
const arr1 = [1, 2, 2, 3, 5, 5, 6, 6]; //const arr2 = [1, 2, 3, 5, 6, 7]; const arr2 = [1, 2, 2, 3, 5, 5]; let includesAll1 = true; let includesAll2 = true; const checkObj1 = { }; const checkObj2 = { }; arr1.forEach((el)=> { if(checkObj1[el] === undefined) { checkObj1[el] = 1; } else { checkObj1[el]++; } }); arr2.forEach((el)=> { if(checkObj2[el] === undefined) { checkObj2[el] = 1; } else { checkObj2[el]++; } }); const check1Keys = Object.keys(checkObj1); const check2Keys = Object.keys(checkObj2); if(check1Keys.length > check2Keys.length) { includesAll2 = false; check2Keys.forEach((key)=> { const value1 = checkObj1[key]; const value2 = checkObj2[key]; if(!arr1.includes(parseInt(key)) || value1 != value2) { includesAll1 = false; } }); } else { includesAll1 = false; check1Keys.forEach((key)=> { const value1 = checkObj1[key]; const value2 = checkObj2[key]; console.log(value1, value2, key); if(!arr2.includes(parseInt(key)) || value1 != value2) { includesAll2 = false; } }); } console.log(includesAll1); console.log(includesAll2);¿Esto resuelve tu problema?
const arr = [1, 2, 3, 5, 6, 7, 2, 10, 2, 3, 2]; const subArr = [1, 2, 2, 3, 2] const contains = subArr.every(num => subArr.filter(n => n == num).length <= arr.filter(n => n== num).length); console.log(contains);Intenta crear esta función:
function containsAll (target, toTest) { const dictionary = {} target.forEach(element => { if (dictionary[element] === undefined) { dictionary[element] = 1; return; } dictionary[element]++; }); toTest.forEach(element => { if (dictionary[element] !== undefined) dictionary[element]--; }) for (let key in dictionary) { if (dictionary[key] > 0) return false; } return true; }Luego invocalo así:
const arr1 = [1, 2, 2, 3, 5, 5, 6, 6] const arr2 = [1, 2, 3, 5, 6, 7] console.log(containsAll(arr1, arr2)) // returns false