DEV Community

Ahmed Ali Tanany
Ahmed Ali Tanany

Posted on

twoSum function JS

returns an array of position pairs where the elements sum to the target parameter

// Array Method to return array of indecies that their values sum is the target.
Array.prototype.twoSum = function (target) {
    // store this value in a normal variable to be captured 
    // by closure
    let self = this;
    // array to store the indices pair.
    let result_two_pairs = [];
    // iterate over each element and sum it with all the next 
    // elements to add the eight indices pair in the result 
    // array
    self.forEach((element) => {
        let start_index = self.indexOf(element);
        this.slice(start_index,).forEach((sec_ele) => {
            if ((element + sec_ele) === target) {
                if (!(result_two_pairs.includes(`(${self.indexOf(element)}, ${self.indexOf(sec_ele)})`))) {
                    result_two_pairs.push(`(${self.indexOf(element)}, ${self.indexOf(sec_ele)})`);
                };
            };
        });
    });
    // return an array containing the indices pair
    return result_two_pairs;
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)