【问题标题】:Filter and uniq array of objects过滤器和唯一的对象数组
【发布时间】:2018-10-23 12:24:38
【问题描述】:

我有一个对象数组。每个对象都有两个字段“类型”和“位置”。我想知道是否有任何对象(在这个数组中)具有相同的“类型”和“位置”(并得到它)。我怎样才能意识到它?我知道如何过滤数组,但是如何与其他对象进行比较?

var array = forms.filter(function (obj) { return obj.type === 100 });

【问题讨论】:

标签: javascript filter uniq


【解决方案1】:

您可以使用Map,对相同类型/位置的对象进行分组,然后筛选长度大于一的分组结果。

var data = [{ type: 'a', position: 1 }, { type: 'b', position: 1 }, { type: 'a', position: 1 }, { type:'a', position: 2 }, { type: 'b', position: 2 }, { type: 'c', position: 1 }, { type:'c', position: 1 }],
    duplicates = Array
        .from(
            data
                .reduce((m, o) => {
                    var key = ['type', 'position'].map(k => o[k]).join('|');
                    return m.set(key, (m.get(key) || []).concat(o));
                }, new Map)
               .values()
        )
       .filter(({ length }) => length > 1);

console.log(duplicates);

【讨论】:

    【解决方案2】:

    这是另一种方法:

    const data = [
      { type: 'a', position: 1 },
      { type: 'b', position: 1 },
      { type: 'a', position: 1 },
      { type: 'a', position: 2 },
      { type: 'b', position: 2 },
      { type: 'c', position: 1 },
      { type: 'c', position: 1 }
    ]
    
    const duplicates = data =>
      data.reduce((prev, el, index) => {
        const key = JSON.stringify({ p: el.position, t: el.type })
        prev[key] = prev[key] || []
        prev[key].push(el)
        if (index === data.length - 1) {
          return Object.values(prev).filter(dups => dups.length > 1)
        }
        return prev
      }, {})
    
    console.log(duplicates(data))

    【讨论】:

      猜你喜欢
      • 2021-04-30
      • 2022-10-23
      • 1970-01-01
      • 2016-12-20
      • 2021-10-30
      • 1970-01-01
      • 1970-01-01
      • 2021-02-26
      • 2017-09-08
      相关资源
      最近更新 更多