compare two array value and remove the duplicate value and store another array lodash

how to compare two array value and remove the duplicate value and store another array using lodash for example

var array1=['1', '2', '3', '4']
var array2=['5', '1', '8', '10', 3]

var result = ['2','4','5','8','10']

1 answer

  • answered 2018-01-12 07:26 Nina Scholz

    Just concat the arrays and check the indices from left and right side. If equal, take the unique value.

    This solution takes only '3' for both arrays.

    var array1 = ['1', '2', '3', '4'],
        array2 = ['5', '1', '8', '10', '3'],
        result = array1.concat(array2).filter((v, _, a) => a.indexOf(v) === a.lastIndexOf(v));
    
    console.log(result);

    With lodash's _.xor

    Creates an array of unique values that is the symmetric difference of the given arrays. The order of result values is determined by the order they occur in the arrays.

    var array1 = ['1', '2', '3', '4'],
        array2 = ['5', '1', '8', '10', '3'],
        result = _.xor(array1, array2);
    
    console.log(result);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>