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

心已入冬 提交于 2021-02-08 10:22:04

问题


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:


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>


来源:https://stackoverflow.com/questions/48221473/compare-two-array-value-and-remove-the-duplicate-value-and-store-another-array-l

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!