Home > Software engineering >  How to compare 2 arrays of numbers and return unique values
How to compare 2 arrays of numbers and return unique values

Time:10-18

I have 2 arrays that contain numbers as elements. I want to compare them to each other and push any unique values onto a new array. I then want to return that new array. I have tried debugging with logging values to the console to view what is happening, but the function does not push any values on to the new array. I think the issue could be with the use of the 'in' keyword.

//find the unique values in these arrays
let array1 = [1,2,2,2,3]
let array2 = [1,2,2,4]

function unique(a, b) {
    let returnArray = []
    //this for loop adds any elements from array1 that are not in array2 to returnArray
    for (let i = 0; i< a.length; i  ) {
        if (!a[i] in b) { 
            returnArray.push(a[i])
        }
    }
    //this for loop adds any elements from array2 that are not in array1 to returnArray
    for (let i = 0; i< b.length; i  ) {
        if (!b[i] in a) {
            returnArray.push(b[i])
        }
    }
    return returnArray
}
console.log(unique(array1, array2))

CodePudding user response:

let array1 = [1,2,2,2,3]
let array2 = [1,2,2,4]

function unique(a, b) {
   return [...new Set([...a, ...b])]
}
console.log(unique(array1, array2))

CodePudding user response:

You would have to use the Array#includes method instead of x in y; when using the in operator with arrays, you must specify the index, not the element itself:

//find the unique values in these arrays
let array1 = [1,2,2,2,3]
let array2 = [1,2,2,4]

function unique(a, b) {
    let returnArray = []
    //this for loop adds any elements from array1 that are not in array2 to returnArray
    for (let i = 0; i< a.length; i  ) {
        if (!b.includes(a[i])) { 
            returnArray.push(a[i])
        }
    }
    //this for loop adds any elements from array2 that are not in array1 to returnArray
    for (let i = 0; i< b.length; i  ) {
        if (!a.includes(b[i])) {
            returnArray.push(b[i])
        }
    }
    return returnArray
}
console.log(unique(array1, array2))

Alternatively.....

You can use the Array#filter() method, as in this answer, for each part of the function and combine the results, [...res1,...res2]:

const
    array1 = [1,2,2,2,3],
    array2 = [1,2,2,4];

function unique(a, b) {
    return [
        ...a.filter(e => !b.includes(e)),
        ...b.filter(e => !a.includes(e))
    ];
}

console.log( unique(array1, array2) );

  • Related