xxxxxxxxxx
let sum = (para) => para.reduce((d,b) => d + b);
xxxxxxxxxx
const arr = [1, 2, 3, 4];
const sum = arr.reduce((a, b) => a + b, 0);
// sum = 10
xxxxxxxxxx
// codewars solution
// leetcode solution
// and more
function sum(arr) {
return arr.reduce( (x,y) => x+y, 0);
}
sum([1, 2, 3, 4]);
// 10
sum([2, 4, 1, 3, 5]);
// 15
// enjoy :)
javascript built in sum function
xxxxxxxxxx
const numbers = [1,2,3,4,5] ;
const sum = numbers.reduce((total, current)=> total+current, 0);
console.log(sum);
// output : 15
xxxxxxxxxx
let arr = [2, 4, 1, 3, 5];
let result = 0;
for (let i = 0; i < arr.length; i++) {
result += arr[i];
}
console.log(result); // 15
xxxxxxxxxx
let sum1 = (arr) => arr.reduce( (x,y) => x+y);
console.log(sum1([2, 4, 9]));
console.log(sum1([15, 200, 18, 0, 18, 18]));
console.log(sum1([100, 4, 17, 29, 81]));
xxxxxxxxxx
function sumNumbers(numbers) {
var sum = 0;
for (let i = 0; i < numbers.length; i++) {
var elements = numbers[i];
sum = sum + elements;
}
return sum;
}
const numbers = [2, 3, 4, 5, 2, 4];
console.log(sumNumbers(numbers));
//Output: 20
xxxxxxxxxx
const array = [1, 2, 3];
const result = array.reduce((accumulator, current) => accumulator + current, 0);
// result === 1 + 2 + 3;
xxxxxxxxxx
export default function PreviewTable({ tableData }) {
const totalSum = tableData?.reduce((current, next) => {
return +current.itemPrice + +next.itemPrice;
});
// console.log(totalSum);
// Format the totalSum with commas
const formattedTotalSum = totalSum?.toLocaleString();
// Use formattedTotalSum where you want to display the total sum with commas ie; $1,191
console.log(formattedTotalSum);