Get the indexes of javascript array elements that satisfy condition - nearest elements sum

Viewed 23

Is there a way to use reduce method to get a indexes of 2 nearest array elements that satisfy condition (sum of these elements).

This is my solution, but I believe there should be more elegant and short solution. Any suggestions?

function indexes(sum, data) {
  for(let i = 0; i < data.length; i++) {
    if(data[i] + data[i+1] === sum) {
      return [i, i+1]
    } 
  } return 'no match'
}
0 Answers
Related