'i want to do sum of two arrays ,and the sum have to start calculate values from right to left for both the arrays
i want to sum of two arrays where if my first array has 2 elements and 2nd array has 4 elements so the problem is it is sum the starting elements of both arrays,, but i want the sum should be start calculating from right to left for both the arrays and if the value of each element is suppose 11 so it should remain the last 1 and the first 1 should go up with next element calculation such as my expected result is 1234+5678=6912 in new array = [6,9,1,2] here is my code-
const Arr1 = [1, 2, 3, 4]; const Arr2 = [5, 6, 7, 8];
function sumArr(A1, A2) {
let A3 = [];
for (let i = 0; i < Math.max(A1.length , A2.length); i++) {
A3.push((A1[i] || 0) + (A2[i] || 0));
}
return A3;
}
console.log(sumArr(Arr1, Arr2))
Solution 1:[1]
I'm not sure if I got the question right
But here a more generic function that I hope does what you are expecting to
const Arr1 = [1, 2, 3, 4];
const Arr2 = [5, 6, 7, 8];
const Arr3 = [9, 10]
//more general with
const sumArray = (...arr) => {
const length = Math.max(...arr.map(a => a.length))
return Array(length)
.fill(0)
.map((_, i) => {
return arr.reduce((sum, a) => sum + (a[i] || 0) , 0)
})
}
console.log(sumArray(Arr1, Arr2))
console.log(sumArray(Arr1, Arr3))
console.log(sumArray(Arr1, Arr2, Arr3))
Here a different version based on @RenauldC5 response
const Arr1 = [1, 2, 3, 4];
const Arr2 = [5, 6, 7, 8];
const Arr3 = [9, 10]
//more general with
const sumArray = (...arr) =>
arr.reduce((res, a) => res + parseInt(a.join('')), 0)
.toString()
.split('')
.map(n => parseInt(n))
console.log(sumArray(Arr1, Arr2))
console.log(sumArray(Arr1, Arr3))
console.log(sumArray(Arr1, Arr2, Arr3))
Solution 2:[2]
I guess the right approach would be to
- Change array to number
- Do the classic sum
- Split the number into array
const Arr1 = [1, 2, 3, 4];
const Arr2 = [5, 6, 7, 8];
const num1 = parseInt(Arr1.join(''))
const num2 = parseInt(Arr2.join(''))
const total = num1 + num2
const Arr3 = total.toString().split('').map(x => parseInt(x))
console.log(Arr3)
Solution 3:[3]
This would work, but both the array should have same number of elements. If your array length is not equal, you can add 0 for the empty space and this code will work on that too.
const a1 = [1, 2, 3, 4]
const a2 = [5, 6, 7, 8]
let carry = 0
const sum = []
for(let i = a1.length-1; i >= 0; i--){
let num = a1[i] + a2[i] + carry
let numArr = num.toString().split('')
if(numArr.length > 1){
carry = Number(numArr[0])
sum.push(Number(numArr[1]))
} else{
carry = 0
sum.push(Number(numArr[0]))
}
}
sum.reverse()
console.log(sum)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | RenaudC5 |
| Solution 3 | p4avinash |
