Can anyone help me how to totalize/Collect positive and negative numbers in javascript? What metodes shud I use
Some useful methods could be filter
and reduce assuming you are referring to an array of numbers that you want to totalize [sic] (I assume you mean sum):
const nums = [5, 3, -2, 0, 9, -8, 7] const positiveNumsTotal = nums.filter(num => num > 0).reduce((a, b) => a + b, 0) const negativeNumsTotal = nums.filter(num => num < 0).reduce((a, b) => a + b, 0) const overallTotal = nums.reduce((a, b) => a + b, 0) console.log(`nums array: ${JSON.stringify(nums)}`) console.log(`Postive number total: ${positiveNumsTotal}`) console.log(`Negative numbers total: ${negativeNumsTotal}`) console.log(`Overall total: ${overallTotal}`)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.