Home > other >  How to summarize total number in an array object
How to summarize total number in an array object

Time:09-28

const dataAll = [ {id: 1, slp: { total: '3' }},{id: 2, slp: { total: '6' }},{id: 3, slp: { total: '5' }} ]

const res = dataAll.map((singleData) => singleData.data.slp.total);
const theres = JSON.stringify(res);
console.log(theres);

How can I add up all the total numbers from the array above? so I can get the total of 3 6 5 = 14

and to get a number of the total number of an array in .length total of 3 example

CodePudding user response:

You can easily add them using reduce and take the length as dataAll.length

const dataAll = [
  { id: 1, slp: { total: "3" } },
  { id: 2, slp: { total: "6" } },
  { id: 3, slp: { total: "5" } },
];

const total = dataAll.reduce((acc, curr) =>  curr.slp.total   acc, 0);
const length = dataAll.length;

console.log(total, length);

CodePudding user response:

You should be able to use reduce.

const dataAll = [ {id: 1, slp: { total: '3' }},{id: 2, slp: { total: '6' }},{id: 3, slp: { total: '5' }} ]
const sum = dataAll.reduce(((total, b) => total   parseInt(b.slp.total, 10)), 0);
const totalElements = dataAll.length;
console.log(sum, totalElements)

CodePudding user response:

try this:

const dataAll = [{ id: 1, slp: { total: '3' } }, { id: 2, slp: { total: '6' } }, { id: 3, slp: { total: '5' } }]
let total = 0
dataAll.map((singleData)=>{
    total  = parseInt(singleData.slp.total)
})
//Use whatever hook you need here to store the total value
setTotalHook(total, dataAll.length)
console.log(total)

CodePudding user response:

You can use reduce to sum up values in an array.

const dataAll = [ {id: 1, slp: { total: '3' }},{id: 2, slp: { total: '6' }},{id: 3, slp: { total: '5' }} ]

const res = dataAll.reduce((partial_sum, a) => partial_sum   parseInt(a.slp.total), 0); 
const theres = JSON.stringify(res);
console.log(theres);

CodePudding user response:

For length just check the length property of the array.

To sum up the totals you can use reduce to iterate over the array of objects and add the value of total to the accumulator (initially set to zero) on each iteration. Note: you need to coerce that value to a number.

const data = [ {id: 1, slp: { total: '3' }},{id: 2, slp: { total: '6' }},{id: 3, slp: { total: '5' }} ];

const sum = data.reduce((acc, c) => {

  // Coerce the string value to a number
  // and add it to the accumulator
  return acc   Number(c.slp.total);
}, 0);

console.log(`Length: ${data.length}`);
console.log(`Sum: ${sum}`);

  • Related