typescript 如何从对象数组返回重复元素

9o685dep  于 2023-01-27  发布在  TypeScript
关注(0)|答案(1)|浏览(207)
data= [
  { "id": 0, "name": "name1", "age": 12, "city": "cityA" },
  { "id": 1, "name": "name2", "age": 7, "city": "cityC" },
  { "id": 2, "name": "name3", "age": 23, "city": "cityB" },
  { "id": 2, "name": "name1", "age": 12, "city": "cityA" }
];

我该怎么退那些名字和时间都一样的东西呢?
我正在尝试类似这样东西,但是它返回数组中的每个元素

data.some(d => {
for (const it of form) {
if (it.name == d.name && it.age == d.age) {
arr.push(it)....
a8jjtwal

a8jjtwal1#

您必须确保不与相同的项目进行比较,因为在这些项目中,属性始终匹配:

data= [
  { "id": 0, "name": "name1", "age": 12, "city": "cityA" },
  { "id": 1, "name": "name2", "age": 7, "city": "cityC" },
  { "id": 2, "name": "name3", "age": 23, "city": "cityB" },
  { "id": 2, "name": "name1", "age": 12, "city": "cityA" }
];

const res = data.filter(item => data.some(i => i !== item && item.name === i.name && item.age === i.age))
console.log(res)

如果您不希望第一次出现,则必须检查已处理的元素:

data= [
  { "id": 0, "name": "name1", "age": 12, "city": "cityA" },
  { "id": 1, "name": "name2", "age": 7, "city": "cityC" },
  { "id": 2, "name": "name3", "age": 23, "city": "cityB" },
  { "id": 2, "name": "name1", "age": 12, "city": "cityA" }
];

const [result, _] = data.reduce(([duplicates, checked], el) => {
    checked.some(i => el.name === i.name && el.age === i.age) && duplicates.push(el)
    return [duplicates, [...checked, el]]
  }, [[], []]
)
console.log(result)

基于排序的方法对于这类问题非常有效:

data= [
  { "id": 0, "name": "name1", "age": 12, "city": "cityA" },
  { "id": 1, "name": "name2", "age": 7, "city": "cityC" },
  { "id": 2, "name": "name3", "age": 23, "city": "cityB" },
  { "id": 2, "name": "name1", "age": 12, "city": "cityA" }
];
const sorted = data.sort( (e1, e2) => e1.name.localeCompare(e2.name) || e1.age - e2.age)
const result = sorted.filter( (el, i) => i > 0 && sorted[i-1].name === el.name && sorted[i-1].age === el.age)
console.log(result)

相关问题