[JS Practice] Sum of two array elements equals to target

Title :

Sum of two array elements equals to target

Description:

Write a function that takes an array of numbers (integers for the tests) and a target number. It should find two different items in the array that, when added together, give the target value. The indices of these items should then be returned in an array like so: [index1, index2].

The input will always be valid (numbers will be an array of length 2 or greater, and all of the items will be numbers; target will always be the sum of two different items from that array).

Example

twosum([1,2,3], 4); // must return [0, 2]

My solution :

function twoSum(numbers, target) {
  var arr = [];
  var len = numbers.length;
  for(var i=0; i< len; i++) {
    for(var j=i+1; j< len; j++) {
      if(numbers[i]+numbers[j] == target) {
        arr[0] = i;
        arr[1] = j;
        return arr;
      }
    }
  }
}

Ref. from codewars

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s