You can also locate pairs with a specified difference using JavaScript: function findPairs ( arr , k ) { let numMap = { } ; let pairs = [ ] ; for ( let i = 0 ; i < arr . length ; i ++ ) { let target = k + arr [ i ] ; if ( numMap [ target ] ) { pairs . push ( [ arr [ i ] , target ] ) ; } numMap [ arr [ i ] ] = true ; } return pairs ; } let arr = [ 1 , 7 , 5 , 9 , 2 , 12 , 3 ] ; let k = 2 ; console . log ( findPairs ( arr , k ) ) ; When you execute the function with the example array, the output will be: [[7,9], [5,7], [2,1], [3,1]] These are the pairs that have a difference of 2.