Interfaz -
interface I { name: string; age: number; size: string; location?: string; }Matrices vacías -
let firstArrayMatches: I[] = []; let firstArrayUnmatches: I[] = []; let secondArrayMatches: I[] = []; let secondArrayUnmatches: I[] = [];arreglos-
const firstArray: I[] = [ { name: 'daniel', age: 30, size: 'm' }, { name: 'tamir', age: 30, size: 'm' }, ] const secondArray: I[] = [ { name: 'daniel', age: 30, size: 's' }, { name: 'ariel', age: 28, size: 'm' }, ]Cree un nuevo mapa a partir de la segunda matriz (Ignore la segunda cadena, es para otra cosa en el código mt real) -
const map = new Map<string, string>( secondArray.map( ({ name }) => [ name, 'firstArray' ]) )Ejecutar en la primera matriz -
for (const o of firstArray) { const match = map.get( o.name ) if(match) { firstArrayMatches.push(o); } else { firstArrayUnmatches.push(o); } }Tronco -
Primera matriz - console.log(JSON.stringify(firstArrayMatches))
"match: [{"name":"daniel","age":30,"size":"m"}]" Segunda matriz: console.log(firstArrayUnmatches)
[{ "name": "tamir", "age": 30, "size": "m" }]En este momento, mi función solo puede devolver coincidencias y no coincidencias de la primera matriz, ¿cómo puedo obtener las coincidencias y no coincidencias de la segunda matriz?
La siguiente solución funcionará solo si no hay duplicados en el nombre de secondArray. (Lo espero porque creas un Mapa a partir de él)
// create index of second array const secondArrayIndexes = Array.from(map.keys()); // OR const secondArrayIndexes = secondArray.map(({ name }) => name); for (const o of firstArray) { // get index of o.name const match = secondArrayIndexes.indexOf(o.name); if (match >= 0) { firstArrayMatches.push(o); secondArrayMatches.push(...secondArray.splice(match, 1)); } else { firstArrayUnmatches.push(o); } } // finally secondArray become secondArrayUnmatches // you should create copy first if you use secondArray after this secondArrayUnmatches = secondArray;