# Two Sum algorithm in Javascript Hi, here is the solution for the next problem: “Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.”

Example:

``````Given nums = [2, 7, 11, 15], target = 9,

Because nums + nums = 2 + 7 = 9,
return [0, 1]``````

Solution:

``````// Main function
let twoSum = (nums, target) => { // receive an array and the target (number)parameters
// First "for" is to check position by position of the nums array starting from 0 position
for (let i = 0; i < nums.length; i++) {
// Second "for" will go through next position of the nums array
// ultil finish the rest of the positions in the array
for (let j = i + 1; j < nums.length; j++) {

// In every next position of the nums array will check if
// the current position (first "for" loop positions + current position of the second "for" loop)
// are the same as target parameter
if (nums[i] + nums[j] === target) { // If is true then go inside the if
// At this point the function will finish
return [i, j]; // and will return that index's inside in array format
}
// If the condition is false then continue with the next position in this second "for"
}

}
};

twoSum([2, 7, 11, 15], 9);``````

Result:

``twoSum([3, 2, 3], 6);``

Result:

By Cristina Rojas.