I have this problem:
Given an array of integers
numsand an integertarget, return the indices of two numbers that add up totarget.
Example 1:
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Output: Because nums[0] + nums[1] == 9, we return [0, 1].
With the code below was able to get the values added in array using set and Map
What I need help is to return the indices
const arr = [{key1: 2}, {key1: 7}, {key1: 11}, {key1: 15}];
const k = 9;
const valueSet = new Set(arr.flatMap((x) => Object.values(x)));
const valueArray = [...valueSet];
valueArray.forEach((v1, i1) => {
for (let i2 = i1 + 1; i2 < valueArray.length; i2++) {
if ((v1 + valueArray[i2]) === k) {
// Return the indices
return valueArray[i2];
}
}
});
You have to parse and find the combination of indexes which gives you the sum.
Below code will help you
const arr = [{ key1: 2 }, { key1: 7 }, { key1: 11 }, { key1: 15 }];
const k = 9;
let valueSet = new Set(arr.flatMap((x) => Object.values(x)));
let valueArray = [...valueSet];
let indices;
let isFound = false;
// valueArray.forEach((v1, i1) => {
for (let i1 = 0; i1 < valueArray.length && !isFound; i1++) {
for (let i2 = i1 + 1; i2 < valueArray.length && !isFound; i2++) {
if ((valueArray[i1] + valueArray[i2]) === k) {
//Return the Indices
indices = [i1, i2];
isFound = true;;
}
}
}
console.log(indices);
The answer provided by Nitheesh works well. As for an explanation as to why your initial approach was not successful:
Using forEach to iterate over an array is different than using traditional for loops, in that the callback function is called for every element on the array. Using return in a forEach loop just breaks out of that particular element's callback, but not the entire iteration (hence, a return in a forEach loop behaves similarly to a continue in a for (...) loop.
You can read more about it here.
First you need to get the array with the values from your array with keys [{key1: 2},{key1: 7},{key1: 11},{key1: 15}];. Then you loop the value array and return the index if the condition (nums[i] + nums[j] == target) => (7 + 2 == 9) is true.
const arr = [{key1: 2},{key1: 7},{key1: 11},{key1: 15}];
const k = 9;
nums = arr.map((o) => {
return Object.values(o)[0]
})
const 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(nums, k))