比较两个数组值并删除重复的值并存储另一个数组 [英] compare two array value and remove the duplicate value and store another array lodash

查看:31
本文介绍了比较两个数组值并删除重复的值并存储另一个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

这篇关于比较两个数组值并删除重复的值并存储另一个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆