使用reduce可以删除对象中的偶数

时间:2019-05-30 21:20:46

标签: javascript object reduce

我得到了一个数字数组。我创建了一个名为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;

必须返回奇数计数的键。

解决方案:

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));
}

3 个答案:

答案 0 :(得分:1)

您可以使用Object.entries来获取整数,然后使用filter项,其值是奇数,然后使用Object.fromEntries从这些项中重构新的Object:

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)

答案 1 :(得分:0)

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

答案 2 :(得分:0)

我知道已经有不错的答案了,但是正如问题所说的“使用减少”,我认为尝试仅使用last_updt_ts来做到这一点很有趣:

data