Created
June 6, 2019 12:10
-
-
Save JeffOgah/4d3a6f2b86cd8f0a283c0c335491fac2 to your computer and use it in GitHub Desktop.
Function to return an array containing indexes of 2 number that sum up to a given limit otherwise return empty array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| function getIndicesOfItemWeights(arr, limit) { | |
| for (let num in arr) { | |
| var difference = (limit - arr[num]) | |
| //Check if a sum is possible | |
| if (arr[num] <= limit && arr.includes(difference)) { | |
| //Sort index in descending order | |
| if (arr.indexOf(arr[num]) < arr.indexOf(difference)) { | |
| return [arr.indexOf(difference), arr.indexOf(arr[num])] | |
| } | |
| return [arr.indexOf(arr[num]), arr.indexOf(difference)] | |
| } | |
| } | |
| return [] | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment