【问题标题】:Remove duplicated objects in JavaScript Array not working删除 JavaScript 数组中的重复对象不起作用
【发布时间】:2022-01-11 09:45:44
【问题描述】:

首先,我知道关于这个问题有很多答案,但我对他们有一些问题,这就是为什么我发布关于这个主题的另一个问题。

这是我的对象数组:

0: {id: 'lAYOUT', label: 'lAYOUT', items: 'val1'}
1: {id: 'tecst', label: 'tecst', items: 'val1'}
2: {id: 'tecst', label: 'tecst', items: 'val1'}

我试图过滤掉只有 2 个值,因为数组中有 2 个相同的对象。我想通过itemslabel 制作独特的对象。

这就是我尝试使用lodash 的方式:

const filteredArray = uniq(nestedItems, (item, key, a) => item.items && item.label)

但它仍然会返回所有 3 个元素。

我也试过这样:

const filteredArray = [...new Set(nestedItems)]

【问题讨论】:

标签: javascript arrays unique


【解决方案1】:

使用Filter 获取特定对象value, index and array。 使用FindIndex 获取特定的数组对象。并比较filter objectfindindex object,如果返回false,则推入新数组!并制作新的独特数组!

试试这个代码!

 let arr = [{ id: 'lAYOUT', label: 'lAYOUT', items: 'val1' },
    { id: 'tecst', label: 'tecst', items: 'val1' },
    { id: 'tecst', label: 'tecst', items: 'val1' }];

    let newArr = arr.filter((value, index, self) =>
      index === self.findIndex((t) => (
        t.label === value.label && t.items === value.items
      ))
    );
    console.log(newArr, 'newArr');

【讨论】:

  • 现在看起来不错!我无法设法让它与labelitems 一起工作,但您的解决方案似乎可以做到! :)
  • 这有非常低性能
【解决方案2】:

您可以使用哈希分组来按多个键进行过滤:

const data = [{ id: 'lAYOUT', label: 'lAYOUT', items: 'val1' }, { id: 'tecst', label: 'tecst', items: 'val1' }, { id: 'tecst', label: 'tecst', items: 'val1' }];

const unique = Object.values(data.reduce((acc, obj) => {
  const hash = `${obj.id}-${obj.label}`;
  acc[hash] = obj;
  return acc;
}, {}));

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

lodash 的结果相同

const data = [{ id: 'lAYOUT', label: 'lAYOUT', items: 'val1' }, { id: 'tecst', label: 'tecst', items: 'val1' }, { id: 'tecst', label: 'tecst', items: 'val1' }];

const result = _.uniqWith(data, (o1, o2) => `${o1.id}-${o1.label}` === `${o2.id}-${o2.label}`);

console.log(result);
.as-console-wrapper{min-height: 100%!important; top: 0}
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.js" integrity="sha512-2iwCHjuj+PmdCyvb88rMOch0UcKQxVHi/gsAml1fN3eg82IDaO/cdzzeXX4iF2VzIIes7pODE1/G0ts3QBwslA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

【讨论】:

    【解决方案3】:

    const data = [
      { id: 'id1', label: 'label1', items: 'items1' }, 
      { id: 'id2', label: 'label2', items: 'items2' },
      { id: 'id1', label: 'label1', items: 'items2' }
    ];
    
    const unique = (...keys) => [
        ...new Map(data.map(item => [keys.map(key => item[key]).join(), item])).values()
    ];
    
    console.log(1, unique('label'));
    console.log(2, unique('label','items'));

    【讨论】:

    • 嘿@Ian 在我的情况下这个解决方案的问题是我需要通过 2 个键使其唯一:itemslabel。有了这个独特的功能,我只能通过 1 个属性使其独一无二。
    • 嗨@Nightcorey 我误解了你的问题的意思,认为只需要一个键来区分,我修改了我的答案,现在你可以使用多个键
    猜你喜欢
    • 2012-09-22
    • 1970-01-01
    • 1970-01-01
    • 2017-08-18
    • 2016-07-02
    • 2014-06-25
    • 1970-01-01
    • 2013-10-30
    • 2018-06-19
    相关资源
    最近更新 更多