反向排序数组的排序索引
sortedIndex for reverse sorted array?
似乎 lodash 的 sortedIndex 需要一个前向排序数组才能使其二叉搜索正常工作。(例如 [0,1,2,4]
(
有没有办法在数组反向排序时使用排序索引?(例如 [4,2,1,0]
(?
> _.sortedIndex( [0,1,2,4], 3 )
> 3
> _.sortedIndex( [4,2,1,0], 3 )
> 4
要使其现在工作,我必须反转数组,找到 sortedIndex,插入新元素,然后取消反转数组。
注意 - 需要一些可以对字符串和数字进行排序的东西。
['A','B','D']
['D','B','A']
并插入'C'
。
_.sortedIndexBy怎么样?
编辑:为了string
比较,String.prototype.charCodeAt(( 可以帮助您将其转换为 Number
,然后可以应用相同的逻辑。
const arr1 = [0, 1, 2, 4];
const arr2 = [4, 2 ,1, 0];
console.log(_.sortedIndex(arr1, 3 ));
// Similar, but with ranking function.
console.log(_.sortedIndexBy(arr2, 3, function(x) {return -x;}));
const charArr = ['D','B','A'];
// Take the first char and convert to Number
let index = _.sortedIndexBy(charArr, 'C', function(x) {
// Type checks. (If you want it to be general to many types..
if (typeof x === 'string') {
return -x.charCodeAt(0);
} else if (typeof x === 'number') {
return -x;
} // else ... for other types.....
});
console.log('To insert char C, put it to index: ', index);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.13.1/lodash.min.js"></script>
或者通过 _.sortedIndex,它也迭代到 4.0.0 之前排名
const arr1 = [0, 1, 2, 4];
const arr2 = [4, 2 ,1, 0];
console.log(_.sortedIndex(arr1, 3));
console.log("Reversed order without ranking func: ",_.sortedIndex(arr2, 3));
// Ranking function to inverse the order.
console.log("Reversed order with ranking func: ",_.sortedIndex(arr2, 3, function(x) {return -x;}));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/1.3.1/lodash.min.js"></script>
感谢皮劳:sortedIndex 期望数组是前向排序的,所以我们不能只是放置反向排序数组并得到arr.length - index
,为了处理不同的场景,我认为我们需要做
- 反向数组 -> 获取排序索引并放置 ->再次反转它。
- 按切片获取反向副本,反向 -> 获取排序索引并通过插入到原始数组的
arr.length - index
-> 进行计算。
以达到预期的结果。
相关文章:
- Javascript排序索引链接数组
- Javascript中的多维数组排序索引问题
- 谷歌地图上的排序/z索引覆盖
- Javascript表排序工作得很好,但对所有索引进行迭代会得到不同的结果
- 对对象保持索引中的值进行排序
- 如何在对象中按值创建排序索引数组
- 根据对象属性对 JavaScript 对象进行排序,但维护索引
- 动态 jquery ui 可排序块的索引/位置
- jQuery - 获取可排序列表的索引
- Javascript 数组 // 从指定索引开始对数组重新排序,同时保持原始顺序
- 如果关联数组从正则表达式返回,则对索引进行排序
- 排序方法和索引
- 对数组和索引进行排序
- 车把:在保留原始排序索引的同时对列表进行排序
- 在 jquery 可排序后定义
- 元素
- 元素的索引
- 元素
- JavaScript 复杂的排序,基于最终排序索引的多个键
- 如何在ExtJS存储中获取记录的预排序索引
- SVG重新排序z索引(Raphael可选)
- 反向排序数组的排序索引
- 根据数组'的排序索引对数组进行排序