This function calculates the sum of two numbers. First, it creates an object that stores the values of each number. Then it loops through the numbers, subtracting the target number from each number. If the result of this subtraction is undefined, that means there is not a target number for that number, so the loop ends and the function returns the object and the appropriate index of the number in the list of numbers.

    function twoSum(nums, target) {
    let numObj = {};
      for (let i = 0; i < nums.length; i++) {
        let complement = target - nums[i];
        if (numObj[complement] !== undefined) {
          return [numObj[complement], i];
        numObj[nums[i]] = i;
    Codiga Logo
    Codiga Hub
    • Rulesets
    • Playground
    • Snippets
    • Cookbooks
    soc-2 icon

    We are SOC-2 Compliance Certified

    G2 high performer medal

    Codiga – All rights reserved 2022.