【问题标题】:Using reduce to delete even numbers in an object使用reduce删除对象中的偶数
【发布时间】:2019-05-31 06:04:16
【问题描述】:

我得到了一个数字数组。我创建了一个名为 counts 的对象,其键是数字,值是这些数字在数组中出现的次数。无法弄清楚如何使用 reduce 删除数字的偶数。

A =  [ 20, 1, -1, 2, -2, 3, 3, 5, 5, 1, 2, 4, 20, 4, -1, -2, 5 ]

n =  5

function findOdd(A) {

  let counts = {};

  for (let i = 0; i < A.length; i++) {
    let num = A[i];
    counts[num] = counts[num] ? counts[num] + 1 : 1;
  }

//counts -> { '1': 2, '2': 2, '3': 2, '4': 2, '5': 3, '20': 2, '-1': 2, '-2': 2 }

  const answer = Object.keys(counts).reduce((object, key) => {
    if (key % 2 !== 0) {
      object[key] = counts[key];
    }
    return object;
  }, {})

  return answer;

必须返回奇数的key。

解决方案:

function findOdd(A) {
  const counts = {};
  for (let i = 0; i < A.length; i++) {
    let num = A[i];
    counts[num] = counts[num] ? counts[num] + 1 : 1;
  }
  Object.keys(counts).forEach(key => {
    if(counts[key] % 2 === 0) {
    delete counts[key];
    }
  });
  return Number(Object.keys(counts));
}

【问题讨论】:

  • 你能展示一些输入和输出的例子吗?
  • 如果是数字数组,为什么不简单的filter()
  • 代码返回一个数组,其中包含键/值对和奇数计数。什么是错误/问题?
  • 您应该在提问时提供您的数据。从代码来看,这是一个多维数组,其成员都与包含它们的数组一样长?
  • 如何过滤并获取每个数字的计数?我创建了对象,所以键是数字,值是计数

标签: javascript object reduce


【解决方案1】:

您可以使用Object.entries 获取整数,然后使用filter 奇数的条目,然后使用Object.fromEntries 从这些条目中重建新的对象:

const countObject = { '1': 2, '2': 2, '3': 2, '4': 2, '5': 3, '20': 2, '-1': 2, '-2': 2 };
const oddEntries = Object.entries(countObject).filter(([key, value]) => value % 2 !== 0);
const oddCountObject = Object.fromEntries(oddEntries)

console.log(oddCountObject)

【讨论】:

    【解决方案2】:

    function findOdd(arr) {
      const counts = {}; // `const` declared objects/arrays are not immutable
      for(let i = 0; i < arr.length; i++) {
        counts[arr[i]] = counts[arr[i]] || 0;
        counts[arr[i]]++;
      }
      Object.keys(counts).forEach(key => {
        if(counts[key] % 2 === 0) {
          delete counts[key];
        }
      });
      return counts;
    }
    
    const array = [1, 2, 3, 4, 5, 6, 1, 1, 4, 5, 4, 9];
    // 1:3, 2:1, 3:1, 4:3, 6:1, 9:1
    // Does not show a `5` key due to there being an even number of fives in `array`
    
    console.log(findOdd(array));

    是的,我知道delete 效率低下,但这没关系,除非它是快速的要求。我相信你可以设置counts[key] = undefinedcounts[key] = null,你可以看到基准here

    【讨论】:

    • 使用了从 Object.keys() 开始的所有内容。必须返回 Number(Object.keys(counts));而不仅仅是计数。非常感谢
    • @benelliott87why Number() ?如果有多个项目的计数是奇数,那将不起作用。
    【解决方案3】:

    我知道已经有很好的答案,但正如问题所说的“使用 reduce”,我认为只使用 reduce 来尝试这样做会很有趣:

    const findOdd = arr => arr.reduce((acc, d, i, list) => {
        if (!acc[d]) {
            acc[d] = 0;
        }
    
        acc[d]++;
    
        if (i === list.length - 1) {
            return Object.keys(acc)
                .reduce((subAcc, key) => ({
                    ...subAcc,
                    ...(acc[key] % 2 === 0 ? {} : {
                        [key]: acc[key]
                    })
                }), {})
        }
        return acc;
    }, {})
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-03-23
      • 1970-01-01
      • 1970-01-01
      • 2013-12-03
      • 1970-01-01
      • 1970-01-01
      • 2016-01-31
      相关资源
      最近更新 更多