简体   繁体   English

JavaScript:在对象数组中循环并使用reduce函数查找特定键的总和

[英]JavaScript: Loop through Array of Objects and Find Sum of Specific Key Using Reduce Function

I have the following object below. 我下面有以下对象。 It contains an array of objects. 它包含一个对象数组。 Each object is a superhero that contains details about the superhero. 每个对象都是一个超级英雄,其中包含有关超级英雄的详细信息。

const superheroes = [
      {
        name: 'Bruce Wayne',
        alias: 'Batman',
        powerLevel: 50,
        universe: 'DC Comics',
        race: 'Human',
      },
      {
        name: 'Wade Wilson',
        alias: 'Deadpool',
        powerLevel: 90,
        universe: 'Marvel Comics',
        race: 'Mutant',
      },
      {
        name: 'Peter Parker',
        alias: 'Spiderman',
        powerLevel: 70,
        universe: 'Marvel Comics',
        race: 'Human',
      },
      {
        name: 'Kristin Wells',
        alias: 'Superwoman',
        powerLevel: 99,
        universe: 'DC Comics',
        race: 'Kryptonian',
      },
      {
        name: 'Barry Allen',
        alias: 'The Flash',
        powerLevel: 80,
        universe: 'DC Comics',
        race: 'Human',
      },
      {
        name: 'Diana Prince',
        alias: 'Wonder Woman',
        powerLevel: 90,
        universe: 'DC Comics',
        race: 'Human',
      },
      {
        name: 'Ororo Munroe',
        alias: 'Storm',
        powerLevel: 85,
        universe: 'Marvel Comics',
        race: 'Mutant',
      },
      {
        name: 'Helen Parr',
        alias: 'Elastigirl',
        powerLevel: 70,
        universe: 'Dark Horse Comics',
        race: 'Human',
      },
    ];

I want to find the average power level of all the superheroes. 我想找到所有超级英雄的平均功率水平。

I tried the code below: 我尝试了下面的代码:

function powerLevelAverage(obj){

  let sum = 0; 
  let objCount = 0;

  return obj.reduce((accumulator, element) => {

    objCount += 1; 
    console.log(objCount)

    sum = accumulator + element.powerLevel

    return sum; 

  }, 0)
  return Math.round(sum/objCount); 
}


const averagePowerLevel = powerLevelAverage(superheroes);

averagePowerLevel

The code appears to return the sum of 634 but does not return the average. 该代码似乎返回634的总和,但不返回平均值。 What am I doing wrong? 我究竟做错了什么?

Note: I want to use reduce modifying function to solve this problem. 注意:我想使用减少修改功能来解决此问题。

There are three mistakes: 有三个错误:

  • You have two return statements in the code. 您在代码中有两个return语句。 So the code will not reach to the second one which gets average. 因此,代码将不会达到平均的第二个代码。
  • You are using reduce() in a wrong way. 您以错误的方式使用了reduce() You are not using accumulator anywhere. 您不在任何地方使用accumulator You are using reduce() like forEach() 您正在使用像forEach()这样的reduce() forEach()
  • You don't need to count each object in reduce() you already have the length of array in form of obj.length 您不需要在reduce()计算每个对象,您已经具有obj.length形式的数组length

A cleaner code can be. 可以使用更干净的代码。

function powerLevelAverage(obj){
  return Math.round(obj.reduce((ac,a) => ac + a.powerLevel,0)/obj.length)
}

Working snippet: 工作片段:

 const superheroes = [ { name: 'Bruce Wayne', alias: 'Batman', powerLevel: 50, universe: 'DC Comics', race: 'Human', }, { name: 'Wade Wilson', alias: 'Deadpool', powerLevel: 90, universe: 'Marvel Comics', race: 'Mutant', }, { name: 'Peter Parker', alias: 'Spiderman', powerLevel: 70, universe: 'Marvel Comics', race: 'Human', }, { name: 'Kristin Wells', alias: 'Superwoman', powerLevel: 99, universe: 'DC Comics', race: 'Kryptonian', }, { name: 'Barry Allen', alias: 'The Flash', powerLevel: 80, universe: 'DC Comics', race: 'Human', }, { name: 'Diana Prince', alias: 'Wonder Woman', powerLevel: 90, universe: 'DC Comics', race: 'Human', }, { name: 'Ororo Munroe', alias: 'Storm', powerLevel: 85, universe: 'Marvel Comics', race: 'Mutant', }, { name: 'Helen Parr', alias: 'Elastigirl', powerLevel: 70, universe: 'Dark Horse Comics', race: 'Human', }, ]; function powerLevelAverage(obj){ return Math.round(obj.reduce((ac,a) => ac + a.powerLevel,0)/obj.length) } console.log(powerLevelAverage(superheroes)) 

You're returning your sum right here, which doesn't account for your division.... 您正要在这里退还您的款项,这不算您的部门...。

Change this to 更改为

function powerLevelAverage(obj){

  let sum = 0; 
  let objCount = 0;

  return obj.reduce((accumulator, element) => {

    objCount += 1; 
    console.log(objCount)

    sum = accumulator + element.powerLevel

    // return sum; // Just get rid of this

  }, 0)
  return Math.round(sum/objCount); 
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用数组作为键来遍历JavaScript中的对象 - using array as key to loop through objects in JavaScript 如何通过键减少对象数组并在javascript中求和 - How to reduce an array of objects by key and sum its values in javascript 遍历对象数组并找到特定的键 - Looping through an array of objects and find a specific key 计算 javascript 中数组对象的总和,TypeError: parseInt(...).reduce is not a function - Calculating sum of array objects in javascript , TypeError: parseInt(...).reduce is not a function Nodejs / javascript - 按键合并对象与减少首选的内部数组 function - Nodejs / javascript - merge objects by key with inner array preferred by reduce function 我在Javascript中有一个对象数组。如何遍历它以查找'fname'键的出现次数 - I have an array of objects in Javascript.How to loop through it to find the number of occurances of 'fname' key Javascript:遍历对象数组以查找键值对并将其呈现在表td中 - Javascript: loop through array of objects to find key value pair and render them in the table td Javascript 中具有 Array.reduce 的相同对象的总和 - Sum of same objects with Array.reduce in Javascript 如何遍历对象数组并在React中获取特定的键值? - How to loop through an array of objects and get specific key values in React? JavaScript 循环遍历所有现有对象以找到 object 密钥 - JavaScript loop through all existing objects to find an object key
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM