Home > Software engineering >  Apply filter and reduce on an array to sum only numbers
Apply filter and reduce on an array to sum only numbers

Time:09-15

I'm trying to write a function that will be called with an array that has information on a person such as their name and then age. I need this function to grab all of the numbers only and then return them then add them all together but I'm having trouble figuring out how to combine filter and reduce (if that's what I even need to use to do this in the easiest way?) so if you could help with that I would be thankful.

Maybe it would be easier for me not to use an arrow function but I just learned about them an hour ago and wanted to try them out.

Apologies for any typos/wrong jargon as my dyslexia gets the better of me sometimes.

What I've got so far;

const totalNums = arr => arr.reduce((a,b) => a   b, 0)

An example of what I want it to return when the function is supplied with the array is

  { name: 'Clarie', age: 22 },
  { name: 'Bobby', age: 30 },
  { name: 'Antonio', age: 40 },
  // returns 92

CodePudding user response:

The first argument in a reduce callback is the "accumulator" - something that takes the initial value and is then passed into each iteration. The second value is the item that's next in the iteration whether that's a number, a string, an object etc.

In your example you're iterating over an array of objects, so you must perform the sum operation using the age value of each of those objects.

const arr = [
  { name: 'Clarie', age: 22 },
  { name: 'Bobby', age: 30 },
  { name: 'Antonio', age: 40 }
];

const total = arr.reduce((acc, obj) => {
  return acc   obj.age;
}, 0);

console.log(total);

CodePudding user response:

You can reduce the object array number as below

const objArr = [
  { name: "Clarie", age: 22 },
  { name: "Bobby", age: 30 },
  { name: "Antonio", age: 40 },
];
console.log(objArr.reduce((prev, curr) => prev   curr.age, 0));

If you want to convert the array of object into array containing only ages:

    const objArr = [
       { name: 'Clarie', age: 22 },
       { name: 'Bobby', age: 30 },
       { name: 'Antonio', age: 40 },
    ];
    console.log(objArr.map(obj => obj.age));
  • Related