javascript sum of two numbers code example
Example 1: two sum javascript
var twoSum = function(nums, target) {
var hash = {};
for(let i=0; i<=nums.length; i++){
var currentNumber = nums[i];
var requiredNumber = target - currentNumber;
const index2 = hash[requiredNumber];
if(index2 != undefined) {
return [index2, i]
} else {
hash[currentNumber] = i;
}
}
};
Example 2: sum of two array in javascript
function sumArrays(...arrays) {
const n = arrays.reduce((max, xs) => Math.max(max, xs.length), 0);
const result = Array.from({ length: n });
return result.map((_, i) => arrays.map(xs => xs[i] || 0).reduce((sum, x) => sum + x, 0));
}
console.log(...sumArrays([0, 1, 2], [1, 2, 3, 4], [1, 2]));
Example 3: add two numbers javascript
var x = 2 + 3;
Example 4: how to add 2 numbers together in javascript
var x = +y + +z;
Example 5: sum of two numbers in javascript
function sumArray(a, b) {
var c = [];
for (var i = 0; i < Math.max(a.length, b.length); i++) {
c.push((a[i] || 0) + (b[i] || 0));
}
return c;
}
Example 6: sum of two array in javascript
function sumArray(a, b) {
var c = [];
for (var i = 0; i < Math.max(a.length, b.length); i++) {
c.push((a[i] || 0) + (b[i] || 0));
}
return c;
}