I have this simple function, and I am just trying to get the length of this array of objects. For instance I want to return 3 in that case below. I could use .length() but I want to explore more with the reduce method.
function getSum(data) {
const totalNum = data.reduce((sum, a) => sum a.id, 0);
return totalNum
}
console.log(getSum([
{id: 'ddd6929eac', isComplete: true},
{id: 'a1dd9fbd0', isComplete: true},
{id: 'afa8ee064', isComplete: false}
]))
Thank you very much :)
CodePudding user response:
Well the equivalent of data.length would be:
data.reduce(sum => sum 1, 0);
But I don't see why you would do that unless you're trying to exclude blank values.
CodePudding user response:
You could add one for each item in the array.
function getSum(data) {
return data.reduce((sum, a) => sum 1, 0);
}
const
data = [{ id: 'ddd6929eac', isComplete: true }, { id: 'a1dd9fbd0', isComplete: true }, { id: 'afa8ee064', isComplete: false }];
console.log(getSum(data));
CodePudding user response:
Simply you can just add index:
const totalNum = data.reduce((sum, a, index) => index 1);
