var unSortedArr = [2, 3, 2, 5, 4, 5, 5, 9, 6, 8, 8, 7]; var sum = 10; function pairMatchingSum (arr, sum) { var start, end, tempSum; var i = 0 ; var j = arr.length - 1; // Create a new Map instance var s = new Map(); var sortedArr = arr.sort(); while (i !== j) { start = sortedArr[i]; end = sortedArr[j]; tempSum = start + end; if (tempSum === sum) { // Add matching pair to the Map. Map does not allow duplicate keys. s.set(start +'-'+ end, true); i++; j--; } else if (tempSum > sum) { j--; } else { i++; } } console.log("Pairs matching the input sum in the given array without duplicates = ", [...s.keys()]); // Pairs matching the input sum in the given array without duplicates = ["2-8", "3-7", "4-6", "5-5"] } pairMatchingSum(unSortedArr, sum);