I encountered a challenge:
I have an array of integers
nums
and an integertarget
. My goal is to find the indices of two numbers in the array that add up to the specifiedtarget
.
Example 1:
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Output: This is because nums[0] + nums[1] equals 9, so we return [0, 1].
After experimenting with some code utilizing set
and Map
, I was able to get the sum of values in the array.
However, my current challenge lies in returning 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];
}
}
});