lodash differenceBy 迭代器过滤数组

lodash的differenceBy方法允许通过自定义迭代器对指定参数1的数组进行过滤。

differenceBy方法

var result=_.differenceBy(array,arr1, 迭代器)
//array为需要过滤的数组
//迭代器会调用array中的每个元素与arr1的每个元素进行比较,去除重复。
//lodash的迭代器支持Array|Function|Object|string,可自行百度或Google"lodash迭代器"

differenceBy例子

//例子1,按对象属性进行过滤
var arr = [{ item: { city: '杭州', area: '华东' } }, { item: { city: '深圳', area: '华南' } }];
var arr1 = [{ item: { city: '广州', area: '华南' } }];
//属性路径item.area
var result = _.differenceBy(arr, arr1,"item.area");
//result结果为:[{"item":{"city":"杭州","area":"华东"}}]

//例子2  函数迭代器,过滤取模后相同的数据
    var arr = [5, 10, 11];
    var arr1 = [20];
    var result = _.differenceBy(arr, arr1, function (a1) {
        return a1 % 5;
    });
//5、10、20取5的模后都是为0,而11取5的模为1
//result结果为:[11]

完整例子

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>lodash differenceBy例子</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no, minimal-ui">
<script src="https://www.itxst.com/package/lodash/lodash.min.js"></script>
<script src="https://www.itxst.com/package/jquery-3.5.1/jquery.min.js"></script>
</head>
<body style="padding:10px;">
<div class="btn" onclick="ck1()">按对象属性过滤</div>
<div class="btn" onclick="ck2()">自定义迭代器</div>
<div id="result"></div>
<script>
//例子1 按对象属性进行过滤
function ck1() {
    var arr = [{ item: { city: '杭州', area: '华东' } }, { item: { city: '深圳', area: '华南' } }];
    var arr1 = [{ item: { city: '广州', area: '华南' } }];
    var result = _.differenceBy(arr, arr1, "item.area");
    $("#result").html(JSON.stringify(result));
}

//例子2 函数迭代器
function ck2() {
    var arr = [5, 10, 11];
    var arr1 = [20];
    var result = _.differenceBy(arr, arr1, function (a1) {
        return a1 % 5;
    });
    $("#result").html(JSON.stringify(result));
}
</script>
<style>
.btn {
    border: solid 1px #ddd;
    background-color: #eee;
    border-radius: 5px;
    padding: 5px 12px;
    text-align: center;
    cursor: pointer;
    display: inline-block;
    margin-right: 8px;
}
.btn:active {
    border: solid 1px #cac9c9;
    background-color: #cac9c9;
}
</style>
</body>
</html>

在线试一试