Home > Back-end >  Finding the symmetric difference in a loop
Finding the symmetric difference in a loop

Time:06-01

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.

CodePudding user response:

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]))

  • Related