【问题标题】:JavaScript Tally multiple elements of an arrayJavaScript 统计数组的多个元素
【发布时间】:2020-01-05 13:49:11
【问题描述】:

我的任务是计数挑战,我应该返回一个包含数组中元素计数的对象。例如

expect(createTally(['a', 'b', 'a'])).to.eql({ a: 2, b: 1 });

所以我已经设法用高阶函数 reduce 来做到这一点,但我希望能够用 for 循环来做到这一点,所以我可以真正看到它是如何工作的,我的 reduce 方法代码如下......

const createTally = items => {
  const counter = items.reduce((acc, curr) => {
    acc[curr] = (acc[curr] || 0) + 1
    return acc
  }, {})
  return counter
}

到目前为止,对于我的 for 循环,我有 ...

const createTally = items => {
  const tally = {};
  let count = 0

  if (items.length > 0) {
    for (let i = 0; i < items.length; i++) {
      if (items[i].length > count) {
        count += count + 1
        console.log(count)
      }

      const key = items[i]
      tally[key] = count
      return tally
    }

  } else {
    return tally;
  }
}

我正在努力增加计数并且没有通过任何测试,除了在传递空数组时能够返回空对象并在给定单个元素时传递 1 个键值对,任何帮助将不胜感激,谢谢

【问题讨论】:

    标签: javascript arrays object for-loop count


    【解决方案1】:

    一个更简单的解决方案会产生类似以下的内容,而无需所有这些 for 循环:

    const createTally = (items = []) => {  
      const tally = {}
    
      items.forEach(key => {
        tally[key] = tally[key] ? tally[key] + 1 : 1
      })
    
      return tally
    }
    
    console.log(createTally(['a', 'b', 'a']))

    【讨论】:

    • if 条件不是必需的。即使没有它,代码也可以工作。 tally[key] = tally[key] ? tally[key] + 1 : 1可以写成tally[key] = (tally[key] || 0) + 1
    【解决方案2】:

    我不太确定您为什么要在 for 循环实现中检查项目的 .length。您需要做的主要事情是使用for 循环遍历您的项目数组。然后检查当前项目是否在您的 tally 对象中。如果已经是,您可以增加其关联的计数器值,如果不是,您可以将其关联的计数器值初始化为 1。

    如果您的数组长度最初为 0(即:空),for 循环将不会迭代,因此如果是这种情况,默认情况下您的代码将返回一个空对象。

    请参见下面的示例(有关详细信息,请参见代码 cmets):

    const createTally = items => {
      const tally = {}; // acts as the `acc`
    
      for (let i = 0; i < items.length; i++) { // loop over indexes in your array
        let current = items[i]; // get current item in your array (curr)
        
        // if statement peforms this logic seen in `.reduce()`: acc[curr] = (acc[curr] || 0) + 1
        if(tally[current]) // if the current item is already a key in your object then...
          tally[current]++ // increment the counter for current item
        else // if the current item isn't an item in your object, then...
          tally[current] = 1; // initialize the counter to 1
      }
      return tally; // return the `tally` (modified by the for loop)
    }
    
    console.log(createTally(['a', 'b', 'a'])); // {"a": 2, "b": 1}
    console.log(createTally([])); // {}

    【讨论】:

      【解决方案3】:

      你已经创建了我不必要的循环和条件。你只需要一个循环和一个 if 条件。

      运行一个循环。检查项目是否已经在对象内。如果存在,则将其增加一。否则将其分配给0,然后它将增加1

      您也不需要在开始时检查数组的长度。考虑如果length0,for 循环甚至不会迭代一次,tally 将是最后返回的空对象。

      const createTally = items => {
         const tally = {};
         for (let i = 0; i < items.length; i++) {
            if (!tally[items[i]]) {
               tally[items[i]] = 0;
            }
            tally[items[i]]++;
         }
         return tally
      }
      
      
      console.log(createTally(['a', 'b', 'a']))

      【讨论】:

        猜你喜欢
        • 2023-02-26
        • 1970-01-01
        • 2018-01-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-04-10
        • 2017-05-29
        • 1970-01-01
        相关资源
        最近更新 更多