function getNums(ints, s) { let arr = [] ints.forEach((val, index) => { const num = s - val const lastIndex = ints.lastIndexOf(num) if (lastIndex > -1 && lastIndex !== index) { if (!arr.length || lastIndex - index < arr[2]) { arr = [index, lastIndex, lastIndex - index] } } }) if (arr.length) { return [ints[arr[0]], ints[arr[1]]] } else { return undefined } } console.log(getNums([10,5,2,3,7,5], 10))