arrays - 通过比较数组 React JS 的元素来唯一的数组
问题描述
我有这个数组
array = [
{id: "one", title: "new 1"},
{id: "two", parent_id: "132132", title: "new 2"},
{id: "three", parent_id: "132132", title: "new 3"},
{id: "four", parent_id: "132132", title: "new 1"},
{id: "one", parent_id: "132132", title: "new 1"}
]
我们需要
array = [
{id: "two", parent_id: "132132", title: "new 2"},
{id: "three", parent_id: "132132", title: "new 3"},
{id: "four", parent_id: "132132", title: "new 1"},
{id: "one", parent_id: "132132", title: "new 1"}
]
我们需要比较元素以获得具有不同避免其他元素的唯一数组
我试过用这个方法
uniqueArray = (arr) => {
return arr.filter((e, i, arr) => arr.findIndex(e2 => Object.keys(e2).every(prop => e2[prop] === e[prop])) === i);
};
解决方案
我更喜欢Array.reduce
这种事情:
const filteredArr = arr.reduce((acc, current) => {
const exists = acc.find(item => item.id === current.id);
if (!exists) {
return acc.concat([current]);
} else {
return acc;
}
}, []);
推荐阅读
- python - Alembic 忽略特定表
- javascript - 如何使用 python 和 javascript 定位文本并将其写入 textarea?
- flutter - (Flutter) 错误:查找已停用小部件的祖先是不安全的。(使用 IFrameElement)
- oracle - Oracle 12c Forms 中是否有用于包装菜单项的属性?
- sql - 计算两个时间记录之间的差异
- c# - 有什么方法可以使 ITicketStore 作用域?
- ascii - 反斜杠 n `\n` 真的是换行符,但被视为换行符吗?
- php - 我在打开时从错误中创建文件夹的模板
- apache-kafka - Kafka 代理从集群中移除且重新分配失败后降低主题复制因子
- postgresql - 为什么在同一个查询中,hash索引被忽略而使用btree索引