使用lodash:
给出这个打字稿代码import * as _ from "lodash/fp";
const range = _.range(0, 1000);
let objects = _.uniq(range.map((i) => {
let foo = "foo";
let bar = "bar";
if (i < 5) {
foo += i.toString(10);
}
if (i > 995) {
bar += i.toString(10);
}
return {
foo,
bar,
};
}));
我原本只希望看到对象
{
"foo": "foo",
"bar": "bar"
}
一次,总共10个元素包含uniq bar
和foo
字符串。
预期产出:
[
{
"foo": "foo0",
"bar": "bar"
},
{
"foo": "foo1",
"bar": "bar"
},
{
"foo": "foo2",
"bar": "bar"
},
{
"foo": "foo3",
"bar": "bar"
},
{
"foo": "foo4",
"bar": "bar"
},
{
"foo": "foo",
"bar": "bar"
},
{
"foo": "foo",
"bar": "bar996"
},
{
"foo": "foo",
"bar": "bar997"
},
{
"foo": "foo",
"bar": "bar998"
},
{
"foo": "foo",
"bar": "bar999"
}
]
但实际上我看到列表中要保留所有元素。好像_.uniq
没有做任何事情。
我想基于identity / equalnes得到一个唯一的数组列表。应删除所有属性组合的所有数组重复项。
我怎样才能做到这一点?
答案 0 :(得分:1)
如果您想要对象的唯一性,可以使用_.uniqWith
:
const withoutDupes = _.uniqWith(_.isEqual, objects);
console.log(
JSON.stringify(withoutDupes, null, 4),
);
至于你的第一个appraoch,请记住_.uniq
不是在处理一组对象,而只适用于简单数组,例如:
const simpleArray = [1, 1, 1, 1, 2, 3];
console.log(_.uniq(simpleArray));
输出:
[ 1, 2, 3 ]