sortedIndex用于反向排序数组?

时间:2016-07-19 02:19:18

标签: javascript arrays sorting lodash

似乎lodash的sortedIndex期望其二进制搜索的前向排序数组起作用。 (例如[0,1,2,4]

当数组反向排序时,有没有办法使用sortedIndexBy? (例如[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'

1 个答案:

答案 0 :(得分:3)

_.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>

感谢pilau: sortedIndex期望数组是前向排序的,所以我们不能只放置反向排序的数组并得到arr.length - index,并且为了处理各种情况,我认为我们需要做任何一种

  • 反向数组 - &gt;得到排序索引和放置 - &gt;再次扭转它。或
  • 通过切片和反向获得反向复制 - &gt;得到排序索引并按arr.length - index计算 - &gt;插入到原始数组。

达到预期效果。

相关问题