Skip to content

Instantly share code, notes, and snippets.

@JeffOgah
Created June 6, 2019 12:10
Show Gist options
  • Select an option

  • Save JeffOgah/4d3a6f2b86cd8f0a283c0c335491fac2 to your computer and use it in GitHub Desktop.

Select an option

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
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