Loops help us perform repetitive tasks or actions based on a condition that either returns true or false. We shall use nested for loops to solve the Two Sum coding challenge in Javascript. Nested for loop is a loop inside another loop. An outer loop executes first and then the inner loop executes.
Let's create a function with two parameters(nums and target) and store it in a new variable twoSum. The parameter nums is an array of integers and the target parameter is an integer. The function returns indices of two numbers when their sum is equal to target.
var twoSum = (nums, target) => {
for (let i=0; i<nums.length; i++) {
for (let j = i+1; j<nums.length;j++) {
if (nums[i] + nums[j] == target) {
return [i,j];
}
}
}
};
console.log(twoSum([2, 7, 11, 15], 9));
Variable i picks the array and variable j picks the individual number. When the function is called, it returns indices [0,1].
Example
Input: nums = [2,7,11,15], target = 9
Output: [0,1] because nums[0] + nums[1] == 9, therefore indices [0,1] are returned.
Conclusion
And now we are good to go, our challenge has been solved.