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

167
Vistas
Finding the symmetric difference in a loop

I need to write a function that can take an indefinite number of arrays containing integer numbers and it should return 1 array which is the accumulative symmetrical difference between those arrays. Only two arrays are compared at a time. So [1, 2, 3], [3, 4, 2], [1, 5, 3] would first result in [1, 4], (comparing the first two arrays), which is then compared to the third and the final result is [4, 5, 3]. I created a loop that does that for the first two arrays, but I don't know how to turn it into an actual loop that performs the same operation on each step. For some reason using arr[i] and arr[i + 1] throws an error. Here's my code so far.

function test(...arr) {
    let accumulator;
    for (let i = 0; i < arr.length; i++) {
        let common = arr[0].filter(a => arr[1].includes(a))
        let arr0 = arr[0].filter(a => !common.includes(a))
        let arr1 = arr[1].filter(a => !common.includes(a))
        let merged = [...arr0, ...arr1]
        accumulator = merged
    }
    return accumulator
}

console.log(test([1, 2, 3], [3, 4, 2], [1, 5, 3]))

Here accumulator is [1, 4], so at this point the entire operation needs to be performed with the next array and the accumulator, which is where I'm stuck at.

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

0

You're iterating with i from 0 to arr.length - 1. arr[i + 1] is arr[arr.length] in the last iteration. It's out of bounds. You could change the loop condition to i < arr.length - 1.

Example:

function test(...arr) {
    let accumulator;
    for (let i = 0; i < arr.length - 1; i++) {
        let common = arr[i].filter(a => arr[i + 1].includes(a))
        let arr0 = arr[i].filter(a => !common.includes(a))
        let arr1 = arr[i + 1].filter(a => !common.includes(a))
        let merged = [...arr0, ...arr1]
        accumulator = merged
    }
    return accumulator
}

console.log(test([1, 2, 3], [3, 4, 2], [1, 5, 3]))

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