简体   繁体   English

如何将数组中的 object 项目元素与 reduce 进行比较?

[英]How comparing object item elements in an array with reduce?

I have array我有数组

 const example = [{ day: 5, month: 1, key: 1 },{ day: 5, month: 1, key: 2 },{ day: 3, month: 3, key: 3 },{ day: 5, month: 1, key: 4 },{ day: 3, month: 3, key: 5 },{ day: 11, month: 4, key: 6 }];

how to check the elements of the day and month when the same?怎样检查元素的天和月的时候是否相同? if the year and month are repeated I would like the result return如果年份和月份重复我希望结果返回

{err:'the same',index:[0,1,2,3]}

My code not working.我的代码不起作用。

const duplicates = Object.entries(array).reduce((acc, item, index) => {
  if (acc[1].year === item[1].year && acc[1].month === item[1].month) {
    return [
      {
        index:[acc[0],acc[1]],
        err: "the same"
      }
    ];
  }
return acc;});
  • Iterate over the array using Array#reduce to get a Map of the day-month as the key and its occurrence indices as the value .使用Array#reduce遍历数组,得到一个Map作为key ,它的出现索引作为value
  • Using Array#filter , get the entries that have more than one index.使用Array#filter ,获取具有多个索引的条目。
  • After that, return the list using Array#map .之后,使用Array#map返回列表。

 const array = [ { day: 5, month: 1, key: 1 }, { day: 5, month: 1, key: 2 }, { day: 3, month: 3, key: 3 }, { day: 5, month: 1, key: 4 }, { day: 3, month: 3, key: 5 }, { day: 11, month: 4, key: 6 } ]; const duplicates = [...array.reduce((map, { day, month }, index) => { const key = `${day}-${month}`; map.set(key, [...(map.get(key) || []), index]); return map; }, new Map).values()].filter(indices => indices.length > 1).map(indices => ({ err: "the same", index: indices })); console.log(duplicates);

I would use the Map constructor to build a map keyed by (unique) year-month values, and where the associated values are arrays of error objects, initialised with an empty index array.我将使用Map构造函数来构建一个 map 由(唯一的)年月值键控,其中关联的值是错误对象的 arrays,初始化为空index数组。 Then populate those index arrays, and get those that have more than one entry.然后填充这些index arrays,并获取具有多个条目的索引。 This involves no reduce :这不涉及reduce

 const example = [{ day: 5, month: 1, key: 1 },{ day: 5, month: 1, key: 2 },{ day: 3, month: 3, key: 3 },{ day: 5, month: 1, key: 4 },{ day: 3, month: 3, key: 5 },{ day: 11, month: 4, key: 6 }]; const map = new Map(example.map(o => [o.month * 100 + o.day, {err: "the same", index: []}] )); example.forEach((o, i) => map.get(o.month * 100 + o.day).index.push(i)); const dupes = Array.from(map.values()).filter(o => o.index.length > 1); console.log(dupes);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM