Search code examples
javascriptarraysecmascript-6xor

Please explain the below JavaScript code which returns the value of the unpaired element from the array?


Below is the working code which returns the value 7 from the array [9, 3, 9, 7, 3, 9, 9], because 7 is the value that does not have the same pair, all other values except 7 have a similar value pair in the array.

But I didn't understand this code, can someone please explain this code line by line. Please...

function check(array) {
        var s = new Set;
        
        array.forEach(v => s.delete(v) || s.add(v));
        
        return s.values().next().value;
    }
    
    console.log(check([9, 3, 9, 7, 3, 9, 9]));

Solution

  • Here it is creating a set first, then, for each element in the array, it checks if that exists in the set, if it does, it removes it from the set (thus, removing a pair)

    when it does not find, then it stores, for it to wait for the next pair

    a simulation here with an array of 5 elements

    array = [1,3,3,2,1]
    
    //first iteration
    v = 1
    set = [1]
    
    //next iteration
    v = 3
    set = [1,3]
    
    //next iteration
    v = 3
    set = [1] // the 3 was deleted
    
    //next iteration
    v = 2
    set = [1,2]
    
    //next iteration
    v = 1
    set = [2] // 1 was deleted
    

    at the end, it gets the element alone in the set (or the first one)

    so a run with an array [4,4,4] will return 4 as the last element has no pair