I am trying to improve in my Problem Solving Skills and would love to get some explanation on what it is that I am doing wrong or if I can get a hand in the right direction. My code below is what I am stuck on.
My problem, I am trying to check within the array if it contains any numbers that will sum up to a total given value. Pretty simple but a bit complex for a beginner.
My first Step is to setup a function with two parameters that accept the array and total amount we want.
const array = [10, 15, 7, 3]; function sumUpTotal(array, total) { }
Then I want to iterate through my array to check each value within the array by using the forEach
method to output each value
const array = [10, 15, 7, 3]; function sumUpTotal(array, total) { array.forEach(value => value) }
Now that I have all the outputs, I am stuck on how I can check if the numbers add up with each other to give out the total we want. Can someone please help.
The Output should be two numbers that add up to the total.
For example, given [10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17.
Advertisement
Answer
Using forEach()
to iterate over each value in the array and includes()
to check if any values further ahead in the array sum to your total you can generate an array of unique sum pairs. By only looking forward from the given iteration one avoids generating duplicate pairings. (eg. avoids [[10, 7], [7, 10]]
for you example input)
forEach()
provides both the value
and the index
of the current iteration, which makes it simple to use the optional, second fromIndex
argument of includes()
to only look ahead in the array by passing index+1
. If a match is found an array of [value, difference]
is pushed to the result array. The return value is an array of sum pairs, or an empty array if there are no matches.
const array = [10, -2, 15, 7, 3, 2, 19]; function sumUpTotal(array, total) { let result = [] array.forEach((value, index) => { let diff = total - value; if (array.includes(diff, index + 1)) result.push([value, diff]); }); return result; } console.log(JSON.stringify(sumUpTotal(array, 17)));
.as-console-wrapper { max-height: 100% !important; top: 0; }