【问题标题】:How to merge an array of objects into one array and then filter out the duplicates如何将一组对象合并到一个数组中,然后过滤掉重复项
【发布时间】:2021-12-10 02:01:57
【问题描述】:

首先,我试图将一个包含许多对象的数组合并为一个数组,其中每个对象的每个键都包含在一个数组中。

最后,应该删除数组中的所有重复项以及任何名为“name”的元素。

输入:

const data = [
  {
    name: '10/20',
    Tyler: 1,
    Sonia: 0,
    Pedro: 0,
  },
  {
    name: '10/23',
    Tyler: 0.5,
    Sonia: 0.25,
    Pedro: 0.75,
    George: 0.5,
  },
];

输出:

["Tyler", "Sonia", "Pedro", "George"]

这是我迄今为止尝试过的:

const mergedData = data.reduce((prev, cur) => {
  const obj = cur[0];
  const keys = Object.keys(obj);
  const names = keys.splice(1);
  return { names };
}, []);

我正在尝试捕获除“name”之外的任何键名并将其添加到最终数组中。但是,这是我卡住的地方,因为我收到了这个错误,TypeError: Cannot convert undefined or null to object

注意:对象可能有不同的长度,包含混合名称,但绝不会有任何重复。

【问题讨论】:

    标签: javascript arrays algorithm


    【解决方案1】:

    一种选择是找到放入集合中的所有键并删除name

    const data = [
      {
    name: '10/20',
    Tyler: 1,
    Sonia: 0,
    Pedro: 0,
      },
      {
    name: '10/23',
    Tyler: 0.5,
    Sonia: 0.25,
    Pedro: 0.75,
    George: 0.5,
      },
    ];
    
    const set = new Set(data.reduce((acc, i) => [...acc, ...Object.keys(i)], []));
    set.delete('name');
    const result = [...set];
    
    console.log(result);

    【讨论】:

      【解决方案2】:

      const data = [
        {
      name: '10/20',
      Tyler: 1,
      Sonia: 0,
      Pedro: 0,
        },
        {
      name: '10/23',
      Tyler: 0.5,
      Sonia: 0.25,
      Pedro: 0.75,
      George: 0.5,
        },
      ];
      
      const result =Array.from(new Set(data.reduce((acc, i) => [...acc, ...Object.keys(i)], [])));
      
      console.log(result)

      【讨论】:

        【解决方案3】:

        如果您可以访问 ES6 方法,则可以使用 Set(在创建时确保唯一值)来执行此操作,如果您愿意,可以通过 Destructuring 将其转换回数组。

        data = [{name: '0', Tyler: '1', Dan: '2', Carl: '3'},  {name: '0', Tyler: '1', Dan: '2', Eric: '3', Danny: '4'}];
        
        const output = (data) => {
          let output = [];
        
          // This makes sure you get each array and then strips just the keys as desired
          data.forEach(item => {
              output = output.
                concat(Object.keys(item))
          });
        
        // This creates the set, strips our dups, and then spreads itself into an array
        return [...new Set(output)]
            // Strip out the 'name' key as needed
            // NOTE: This should be a param instead of hard-coded, but this is easier to show
            .filter(res => res != 'name');
        }
        
        console.log(output(data));

        考虑到它只对整个数组进行一次导航,并且每个对象本身不应该有数百万个属性导致.keys() 出现任何问题,这应该是相当高效的。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-10-30
          • 2020-05-17
          • 2021-11-12
          • 1970-01-01
          • 2023-02-03
          • 1970-01-01
          • 1970-01-01
          • 2019-10-24
          相关资源
          最近更新 更多