比较两个数组值并删除重复的值并存储另一个数组

比较两个数组值并删除重复的值并存储另一个数组

问题描述:

如何比较两个数组值并删除重复值并使用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']

只需连接数组并检查左右两侧的索引即可.如果相等,则取唯一值.

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

对于两个阵列,此解决方案仅需'3'.

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);

使用lodash的 _.xor

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>