首页 > 解决方案 > 通过比较数组 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);
};

标签: arraysreactjs

解决方案


我更喜欢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;
  }
}, []);

推荐阅读