javascript - 多个字段上的sortedIndexBy

标签 javascript underscore.js lodash

使用 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/

相关文章:

javascript - 删除不属于或继承的属性(property)

Javascript:set element.style = element.style 破坏样式?

javascript - react 原生 : set id to a component and get this component's id

javascript - 下划线: Losing reference to collection when filtering

javascript - Backbone.js中如何使用groupBy对集合进行分组?

javascript - 从underscorejs中的循环数组中删除项目

javascript - 如何重置迭代器?

javascript - 在 D3 图中绕轴旋转矩形

javascript - 我如何使用 Lodash 实现这一目标?

javascript - Lodash Debounce 不去抖动