Skip to content

Instantly share code, notes, and snippets.

@jkusachi
Last active November 9, 2016 22:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jkusachi/3e97d938a343760030f01457bad5d483 to your computer and use it in GitHub Desktop.
Save jkusachi/3e97d938a343760030f01457bad5d483 to your computer and use it in GitHub Desktop.
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