Pairwise

In this exercise was given an array arr, to find element pairs whose sum equal the second argument arg and return the sum of their indices.

If multiple pairs are possible that have the same numeric elements but different indices, return the smallest sum of indices. Once an element has been used, it cannot be reused to pair with another.

For example pairwise([7, 9, 11, 13, 15], 20) returns 6. The pairs that sum to 20 are [7, 13] and [9, 11]. We can then write out the array with their indices and values.

Below we’ll take their corresponding indices and add them. 7 + 13 = 20 → Indices 0 + 3 = 3 9 + 11 = 20 → Indices 1 + 2 = 3 3 + 3 = 6 → Return 6

How I solved the problem

In the first line I have a function with two parameters and those parameters is the first argument and second argument, on the second line I am declaring a variable name results and assigned it to the value of zero(0).

On the third line its a for loop which will iterate for the first argument and on the fourth line its another for loop which will iterate for the second argument.

On the fifth line its an if statement to check if the for loop is equal to the second then should break. for(var y = 0; y <arr.length; y++){ if(x === y){ break; } }

On the sixth line its an if statement adding the two indexs of x and y and checks if its equal to the second argument. Therefore I appended the results I got with x and y and deleted.

if(arr[x] + arr[y] === arg){ result += x + y; delete arr[x]; delete arr[y]; }

Conclusion

In this exercise I got to understand about arrays and for loop more and also about delete: The delete operator is one of the less frequently used aspects of the JavaScript language. But there are times when you need delete and nothing else will do. In this drip, we’ll dive into how to use it and how it works. The purpose of delete, as you might imagine, is to delete things. More specifically, it will delete object properties.

Example:

var multiverse = { earth1: “Silver Age”, earth2: “Golden Age” };

delete multiverse.earth2;

// Outputs: { earth1: “Silver Age” } console.log(multiverse);