Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

78
Vistas
Seguimiento de cambios en matriz JS

Creé un script en javascript que debería rastrear todos los cambios entre 2 matrices de cadenas. Por ejemplo: si el elemento se agregó o eliminó en comparación con la primera matriz.

 const initial = ['test', 'color']; const changed = ['5']; const checkArrDiff = (initialArr, changedArr) => { const newElements = []; const removedElements = []; const getDiff = changedArr.reduce((acc, item, idx) => { if (!initialArr.includes(item)) { newElements.push(item) acc.new = newElements } if (!changedArr.includes(initialArr[idx])) { removedElements.push(initialArr[idx]) acc.removed = removedElements } return acc; }, {}) return getDiff; } console.log(checkArrDiff(initial, changed))

En el caso anterior, espero el siguiente resultado:

 { "new": [ "5" ], "removed": [ "test", "color" ] }

Por el momento obtengo un resultado incorrecto. ¿Quién puede ayudar a arreglar el código?

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

RESPUESTA ACTUALIZADA

Por ejemplo, tenemos dos matrices arr1 y arr2 .

 arr1 = ["a", "b", "c"]; arr2 = ["b", "d"];

En las matrices de ejemplo anteriores, eliminé a,c y agregué d , pero en mi código anterior no dará el resultado exacto que esperábamos, porque cuando eliminamos a siguiente elemento b se moverá al índice 0 , por lo que mi código anterior asumirá b como nuevo elemento, pero acaba de cambiar su índice.

Aquí lo resolví insertando un valor undefined en una posición de valor no coincidente con la función de spice .

Ahora detectará valores duplicados y reales. vuelva a verificar con múltiples matrices de ejemplo.

 // new example to check does it work well or not let initial = ["a", "b", "c"]; let changed = ["b", "d"]; console.log(getDifference(initial, changed)); // main function function getDifference(array1, array2) { let result = {removed:[], new:[]}; array1.filter((item, index) => item !== array2[index] ? (result.removed.push(item) && array2.splice(index, 0, undefined)) : null); array2.filter((item, index) => (item !== array1[index] && item !== undefined) ? (result.new.push(item)) : null); return result; }

RESPUESTA ANTIGUA

Dará un resultado preciso al hacer coincidir tanto el número de índice como el valor.

 const initial = ['test', 'color']; const changed = ['5']; console.log(getDifference(initial, changed)); function getDifference(array1, array2) { let result = {removed:[], new:[]}; array1.filter((item, index) => item !== array2[index] ? (result.removed.push(item)) : null); array2.filter((item, index) => item !== array1[index] ? (result.new.push(item)) : null); return result; }

about 4 years ago · Juan Pablo Isaza Denunciar

0

El problema es que itera sobre la matriz modificada que tiene 1 índice mientras intenta verificar 2 índices de la matriz inicial.

Sin embargo, puedes simplificar tu lógica. Creo que esto es lo que quieres.

Con solo 2 llamadas de filtro de matriz, puede definir los elementos eliminados y nuevos.

 const initial = ['test', 'color', 'both']; const changed = ['5', 'both']; const checkArrDiff = (initialArr, changedArr) => { return { new: changed.filter((item) => !initial.includes(item)), removed: initial.filter((item) => !changed.includes(item)) } } console.log(checkArrDiff(initial, changed))

about 4 years ago · Juan Pablo Isaza Denunciar

0

Bueno, usaría un bucle simple para eso y no una reducción por las razones que señaló jabaa

 function checkArrDiff(before,after){ var toReturn={new:[],removed:[]} var extras={new:[],removed:[]} //useless check removed by sensible suggestion by jabaa if(before.length<after.length){ //definitely new things for(let i=before.length;i<after.length;i++){ extras.new.push(after[i]) } } else if(after.length<before.length){ //definitely removed things for(let i=after.length;i<before.length;i++){ extras.removed.push(before[i]) } } var length=after.length>before.length?before.length:after.length //lowest length between the 2 for(let i=0;i<length;i++){ if(before[i]!=after[i]){ toReturn.new.push(after[i]) toReturn.removed.push(before[i]) } } toReturn.new.push(...extras.new) toReturn.removed.push(...extras.removed) return toReturn } //example console.log(checkArrDiff(['test', 'color'],['5']))

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda