使用One Liner在对象阵列中查找唯一
const uniqueBy = (x,f)=>Object.values(x.reduce((a,b)=>((a[f(b)]=b),a),{}));
// f -> should must return string because it will be use as key
const data = [
{ comment: "abc", forItem: 1, inModule: 1 },
{ comment: "abc", forItem: 1, inModule: 1 },
{ comment: "xyz", forItem: 1, inModule: 2 },
{ comment: "xyz", forItem: 1, inModule: 2 },
];
uniqueBy(data, (x) => x.forItem +'-'+ x.inModule); // find unique by item with module
// output
// [
// { comment: "abc", forItem: 1, inModule: 1 },
// { comment: "xyz", forItem: 1, inModule: 2 },
// ];
// can also use for strings and number or other primitive values
uniqueBy([1, 2, 2, 1], (v) => v); // [1, 2]
uniqueBy(["a", "b", "a"], (v) => v); // ['a', 'b']
uniqueBy(
[
{ id: 1, name: "abc" },
{ id: 2, name: "xyz" },
{ id: 1, name: "abc" },
],
(v) => v.id
);
// output
// [
// { id: 1, name: "abc" },
// { id: 2, name: "xyz" },
// ];