【问题标题】:how to make an array unique using reduce method of javascript如何使用javascript的reduce方法使数组唯一
【发布时间】:2022-01-22 19:45:00
【问题描述】:

我已经创建了一个示例供您理解问题。

let arr = [];
arr.push({
  module_id: 41,
  name: 'first'
}, {
  module_id: 41,
  name: 'second',
  important: true,
}, {
  module_id: 43,
  name: 'third'
});

const lookup = arr.reduce((a, e) => {
  a[e.module_id] = ++a[e.module_id] || 0;
  return a;
}, {});
console.log('lookup is', lookup);

let unique = [];
arr.filter((e) => {

  if (lookup[e.module_id] === 0) {
    unique.push(e)
  }
})

console.log('unique', unique)

首先,我有一个空数组arr,我在其中推入 3 个对象。
注意,module_name。有两个重复,我想使用属性名称为important 的第二个。
我在这里使用reduce 来找出基于module_name 重复的那个。它将返回 1 和 41 的键和 0 的 43。我想同时使用两者,但我不想复制到我的 unique 数组中。目前,我只会推送那些独特的元素,在我们的例子中是module_id: 43
现在如何获取重复值(使用important 属性)?

【问题讨论】:

标签: javascript arrays reactjs object


【解决方案1】:

您可以使用 Map 并仅获取不同的第一个值或具有重要标志的值。

const
    array = [{ module_id: 41, name: 'first' }, { module_id: 41, name: 'second', important: true }, { module_id: 43, name: 'third' }],
    result = Array.from(array
        .reduce(
            (m, o) => m.set(o.module_id, !o.important && m.get(o.module_id) || o),
            new Map
        )
        .values()
    );

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

【讨论】:

    【解决方案2】:

    试试

    let unique = [];
    arr.filter((e) => {
    
      if (lookup[e.module_id] === 0) {
        unique.push(e)
      }
      else if (e.important) {
        unique.push(e)
      }
    })
    

    【讨论】:

      【解决方案3】:

      let arr = [];
      arr.push(
        {
          module_id: 41,
          name: 'first',
        },
        {
          module_id: 41,
          name: 'second',
          important: true,
        },
        {
          module_id: 43,
          name: 'third',
        }
      );
      
      
      const result = arr.reduce(
        (acc, curr) =>
          acc.find((v) => v.module_id === curr.module_id) ? acc : [...acc, curr],
        []
      );
      
      console.log(result);

      【讨论】:

      • 这不会返回具有重要属性的对象。
      • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
      猜你喜欢
      • 2020-06-07
      • 1970-01-01
      • 1970-01-01
      • 2020-10-27
      • 1970-01-01
      • 2017-05-23
      • 2018-12-07
      • 2016-04-01
      • 2021-10-30
      相关资源
      最近更新 更多