Find a pair of elements from an array whose sum equals a given number in javascript:
We can find a pair of elements from an array whose sum equals a given number in javascript in a different way. Listing the easiest methods.
Solution 1 :
- The first thing isĀ to sort an array
- Store the first element of an array
- Store the last element of an array
- Add the first and last element as theSum
- If tempSum === theSum then add the pair as an element to an object
function pairMatchingSum (arr, sum) { var start, end, tempSum; var i = 0 ; var j = arr.length - 1; // Create a new Object instance var pairValues = {}; var sortedArray = arr.sort(); while (i !== j) { start = sortedArray[i]; end = sortedArray[j]; tempSum = start + end; if (tempSum === sum) { // Add matching pair to the Object. Object does not allow duplicate keys. pairValues[start +'-'+ end] = true; i++; j--; } else if (tempSum > sum) { j--; } else { i++; } } console.info("Pairs of values", Object.keys(pairValues)); } var array = [2, 3, 2, 5, 4, 5, 5, 5, 5, 9, 6, 8, 8, 7]; var sum = 10; pairMatchingSum(array, sum);
Solution 2 :
Using the for-loop with HashMap function
let pairMatchingSum = (array, sum) => { let mapObject = {}, mathcingPair = [] for (let i = 0; i < array.length; i++) { if (mapObject[array[i]]) { mathcingPair.push([mapObject[array[i]], array[i]]) } else { mapObject[sum - array[i]] = array[i]; } } return mathcingPair; } console.log(pairMatchingSum([10,20,10,40,50,60,70,30],50));
Also, read What are interfaces?
One thought on “Find a pair of elements from an array whose sum equals a given number in javascript”
Comments are closed.