I'm trying to do the basic twoSum question from leetcode. My nums
array comes back as undefined throughout this function, and I'm totally lost as to why. I'm sure it's obvious, but I'm having a hard time even troubleshooting it, because no matter where I put console logs in this function, it always says that nums is undefined.
const nums = [2, 7, 11, 15];
const target = 9;
function twoSum() {
if (nums.length > 0) {
while (nums === Number) {
for (let i = 0; i < nums; i++) {
for (let k = 0; k < nums; k++) {
if (i + k == target) {
console.log([i, k]);
} else {
console.log("no result");
}
}
}
}
} else {
console.log("Array is Empty");
}
};
console.log(twoSum());
You need to make the following changes in your code. It should fix your issue
while (nums === Number)
conditioni + k == target
with nums[i] + nums[k] == target
. As i and k are indexes not actual values in array console.log("no result");
in else condition. Instead create a flag and check if it's false then do the console.log Otherwise it will console.log everytime nums[i] + nums[k] !== target
.const nums = [2, 7, 11, 15];
const target = 9;
let flag = false;
function twoSum() {
if (nums.length > 0) {
for (let i = 0; i < nums.length -1; i++) {
for (let k = 1; k < nums.length; k++) {
if (nums[i] + nums[k] == target) {
flag = true;
console.log('indexes', [i, k], 'values', [nums[i], nums[k]]);
}
}
}
if (!flag) {
console.log("No Result")
}
} else {
console.log("Array is Empty");
}
}
twoSum();
Assumed objective
Given an array of integers and a target
, find any pairs of integers in the array whose sum matches the target
.
Code Snippet
const nums = [2, 7, 11, 15];
const target = 9;
const twoSum = (tgt = target, arr = nums) => (
arr.forEach(x =>
arr.forEach(y =>
x + y === tgt && console.log(x, y)
)
)
);
console.log('target = 9');
twoSum();
console.log('target = 4');
twoSum(4);
console.log('target = 30');
twoSum(30);
console.log('target = 55');
twoSum(100) || console.log('no matches');
Explanation
x
y
x
and y
matches target
, then console.log
NOTES
target
of 4
the code prints out 2 2
.