使用 lodash 很简单:
var objects = [{ 'x': 4 }, { 'x': 4 }];
_.sortedIndexBy( objects, {'x':3}, 'x' );
但是当对多个字段进行排序和计算时如何找到索引呢?例如:
var objects = [{ 'x': 4, 'y': 1 }, { 'x': 4, 'y': 3}];
_.sortedIndexBy( objects, {'x':4, 'y':6}, ['x', 'y'] );
(第二个示例不起作用,但表明我正在尝试做的事情)
最佳答案
将 iteratee 更改为自定义函数,该函数计算一个值,其中 x 的值始终优先于 y 的值:
_.sortedIndexBy( objects, {'x':4, 'y':6}, o => o.x * 1000 + o.y );
关于javascript - 多个字段上的sortedIndexBy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46102490/