Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Given a Collection and a search value, find the index of closet matching value, rounding UP
/**
<p>Given a collection (array of objects) and a value, find the index of the closest matching value (rounding UP).</p>
<br/>
<strong.=>example:</strong>
<pre>
var arr = [{ val: 0}, { val: 25}, { val: 50}, { val: 75}, { val: 100}];
Given: 0 // given value to find
Expected: 0 //index
Given: 26
Expected: 2 // using val: 50 as the match
Given: 50
Expected: 2
Given: 74
Expected: 3
</pre>
**/
import { map } from 'lodash';
const arr = [{ val: 0}, { val: 25}, { val: 50}, { val: 75}, { val: 100}];
const findClosestIndex = (collection, searchVal, key = 'value') => (
map(collection, key).reduce((prev, cur, index) => (
(searchVal <= cur && prev == null) ? index : prev
), null)
);
console.log(0, ' is closest to index ', findClosestIndex(arr, 0, 'val'));
console.log(26, ' is closest to index ', findClosestIndex(arr, 26, 'val'));
console.log(50, ' is closest to index ', findClosestIndex(arr, 50, 'val'));
console.log(74, ' is closest to index ', findClosestIndex(arr, 74, 'val'));
console.log(99, ' is closest to index ', findClosestIndex(arr, 99, 'val'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.