Lodash“uniqBy”条件用于减少重复的数组值
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Lodash“uniqBy”条件用于减少重复的数组值相关的知识,希望对你有一定的参考价值。
所以我有一个这种格式的数组集合。
var innitialArray = [
[0:"Hello", 1:"World", 3: "Wow", 4:"I WANT MORE"],
[0:"Hello", 1:"World", 3: "Wow", 4:"MORE I WANT"],
[0:"Meow", 1:"World", 3: "Wow", 4:"MORE I WANT"],
[0:"Meow", 1:"World", 3: "Wow", 4:"I WANT MORE"]
];
我已经尝试使用此代码使用loadash _.uniqBy方法。
let uniq_ws_data = _.uniqBy(ws_data_initial, function (e) {
return e[0];
});
我上面的代码得到的是这个数组:
var uniq_ws_data = [
[0:"Hello", 1:"World", 3: "Wow", 4:"I WANT MORE"],
[0:"Meow", 1:"World", 3: "Wow", 4:"I WANT MORE"],
];
但我的预期结果应该是这样的:
var uniq_ws_data = [
[0:"Hello", 1:"World", 3: "Wow", 4:"I WANT MORE"],
[0:"Meow", 1:"World", 3: "Wow", 4:"MORE I WANT"],
];
也试图改变return e[0] to e[4]
但我得到了这个:
var uniq_ws_data = [
[0:"Hello", 1:"World", 3: "Wow", 4:"I WANT MORE"],
[0:"Hello", 1:"World", 3: "Wow", 4:"MORE I WANT"],
];
有没有办法达到我预期的结果?
使用的代码:
let uniq_ws_data = _.uniqBy(ws_data_initial, function (e) {
return e[0];
});
预期结果 :
var uniq_ws_data = [
[0:"Hello", 1:"World", 3: "Wow", 4:"I WANT MORE"],
[0:"Meow", 1:"World", 3: "Wow", 4:"MORE I WANT"],
];
答案
我不知道你是如何设法运行此代码的,但它在语法上是不正确的。我假设你想让initialArray
成为一个数组数组。
工作范例:
const initialArray = [
["Hello", "World", "Wow", "I WANT MORE"],
["Hello", "World", "Wow", "MORE I WANT"],
["Meow", "World", "Wow", "MORE I WANT"],
["Meow", "World", "Wow", "I WANT MORE"]
];
const result = _.uniqBy(initialArray, _.first);
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
以上是关于Lodash“uniqBy”条件用于减少重复的数组值的主要内容,如果未能解决你的问题,请参考以下文章