简体   繁体   English

在UnderscoreJs中获取数组中数字之间的对象

[英]Get objects between a number in array in UnderscoreJs

I'm looking for a way in Underscore.js to find two numbers that lay between a number in an array. 我正在Underscore.js中寻找一种方法来查找位于数组中的数字之间的两个数字。

Number cannot be < 5 && > 20 or any of the numbers in the list. 数字不能为<5 &&> 20或列表中的任何数字。

I have a working Javascript version 我有一个有效的Javascript版本

 var data = [ { key: 5 }, { key: 10 }, { key: 15 }, { key: 20 } ]; function getBetween(xTest, xyLists) { for (var ic = 0; ic < xyLists.length - 1; ic++) { if (xyLists[ic].key <= xTest && xyLists[ic + 1].key >= xTest) return [xyLists[ic], xyLists[ic + 1]]; }; } console.log(getBetween(9, data)); //expect 5,10 console.log(getBetween(16, data)); //expect 15,20 

I have been trying something like this 我一直在尝试这样的事情

 _.first(_.filter(xyLists, 
   function (item) { return item.key >= xTest; }), 2);

If the array is already sorted by the key value, then you need to compare the previous or the next value also like 如果数组已经按键值排序,那么您需要比较上一个或下一个值,例如

 var data = [{ key: 5 }, { key: 10 }, { key: 15 }, { key: 20 }]; function getBetween(xTest, xyLists) { return _.map(_.filter(xyLists, (item, idx, arr) => (item.key <= xTest && (arr[idx + 1] || {}).key >= xTest) || (item.key >= xTest && (arr[idx - 1] || {}).key <= xTest)), item => item.key) //return xyLists.filter((item, idx, arr) => (item.key <= xTest && (arr[idx + 1] || {}).key >= xTest) || (item.key >= xTest && (arr[idx - 1] || {}).key <= xTest)).map(item => item.key) } snippet.log(JSON.stringify(getBetween(9, data))); //expect 5,10 snippet.log(JSON.stringify(getBetween(16, data))); //expect 15,20 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore.js"></script> <!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 --> <script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM