I'm trying to figure out how to dynamically doing a deep looping over an array.
Lets say i have a function that takes an array of numbers and a total number, it will loop over the array and will return a tuple of the numbers that together make the sum of the total:
const sumOfTwo = (arr, total) => {
let map = {};
for (let currentNum of arr) {
if (map[currentNum] !== undefined) {
return [map[currentNum], currentNum]
} else {
map[total - currentNum] = currentNum;
}
}
return [];
}
const num = 6
const arr = [4, 5, 2, 3, 1];
const result = sumOfTwo(arr, num);
console.log(result); // [4, 2]
Now if i want to create the same function but that finds a sum of three numbers, i will have to do a nested loop:
function sumOfThree(arr, total) {
for (let i = 0; i < arr.length; i++) {
let processed = {};
let firstNum = arr[i];
let firstDelta = total - firstNum;
for (let j = i + 1; j < arr.length; j++) {
let secondNum = arr[j];
let secondDelta = firstDelta - secondNum;
if (processed[secondDelta]) {
return [firstNum, secondNum, secondDelta];
}
processed[secondNum] = true;
}
}
return [];
}
const arr = [1, 2, 3, 4];
const sum = 6;
const result = sumOfThree(arr, sum);
console.log(result); // [1, 3, 2]
If i want a sumOfFour function, i guess i need another nested loop and so on.
What i actually want is to create a generic function sumOf that will take the array, the total but also that number of numbers it should add up to the total. I was thinking of doing a recursive flow but got stuck on the very first line, now i'm not so sure it can be done.
Any suggestion would be much appropriated
._sumlodash.com/docs/4.17.11#sum