0

Using the code from this answer to find the closest value in an array: https://stackoverflow.com/a/62159057

func closestMatch(values: [Int64], inputValue: Int64) -> Int64? {
   return (values.reduce(values[0]) { abs($0-inputValue) < abs($1-inputValue) ? $0 : $1 })
}

How can I get the index of the item that matches closest instead of its value?

viedev
  • 869
  • 1
  • 6
  • 16

2 Answers2

1

Because the array is sorted, a fast solution would be to do a binary search.

Should be easy to modify this implementation (or others in the same post) to fit your purpose.

meaning-matters
  • 21,929
  • 10
  • 82
  • 142
0

Solved it with firstIndex. Not super elegant but it works.

func closestMatch(values: [Int], inputValue: Int) -> Int? {
    let match = values.reduce(values[0]) { abs($0-inputValue) < abs($1-inputValue) ? $0 : $1 }
    let index = values.firstIndex(where: {$0 == match})
    return index
}
viedev
  • 869
  • 1
  • 6
  • 16