Trying to solve symmetric difference using Javascript

后端 未结 16 1438
伪装坚强ぢ
伪装坚强ぢ 2020-11-29 10:12

I am trying to figure out a solution for symmetric difference using javascript that accomplishes the following objectives:

  • accepts an unspecified number of ar
16条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-29 10:38

    Alternative: Use the lookup inside a map instead of an array

    function sym(...vs){
        var has = {};
        //flatten values
        vs.reduce((a,b)=>a.concat(b)).
            //if element does not exist add it (value==1)
            //or mark it as multiply found value > 1
            forEach(value=>{has[value] = (has[value]||0)+1});
        return Object.keys(has).filter(x=>has[x]==1).map(x=>parseInt(x,10));
    }
    console.log(sym([1, 2, 3], [5, 2, 1, 4],[5,7], [5]));//[3,4,7])
    

提交回复
热议问题