【问题标题】:sortedIndex for reverse sorted array?sortedIndex 用于反向排序数组?
【发布时间】:2016-07-19 02:19:17
【问题描述】:

似乎 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'

【问题讨论】:

    标签: javascript arrays sorting lodash


    【解决方案1】:

    _.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,为了处理不同的场景,我认为我们需要这样做

    • 反转数组 -> 获取排序索引并放置 -> 再次反转它。或
    • 通过切片和反向获取反向副本 -> 获取排序索引并按arr.length - index 计算 -> 插入到原始数组。

    达到预期的效果。

    【讨论】:

    • 好主意!唉,我有时需要以这种方式对字符串进行排序。 ['A','B','D'] 插入 ['D','B','A'] 并插入 'C'。
    • 针对string 案例更新。
    • 但是对于较长的字符串('AAA'、'AAB'、'AAC'),必须遍历字符串来转换每个字符。我担心到那时反转可能会更快。
    • 在使用sortedIndex的时候,你知道数组是不是逆序的吗?如果是,您可以按正常排序获取值,然后使用realIndex = length - index; 获取反向数组中的位置:P。
    • @fuyushimoya _.sortedIndex([40, 30, 10], 20); 产生 0。数组长度 (3) - 0 等于 3。结果数组将是 [40, 30, 10, 20],这意味着 realIndex = length - index; 不起作用 - 除非我遗漏了什么当然:)
    猜你喜欢
    • 1970-01-01
    • 2019-01-09
    • 1970-01-01
    • 2013-03-20
    • 1970-01-01
    • 1970-01-01
    • 2023-02-21
    • 2014-05-15
    • 1970-01-01
    相关资源
    最近更新 更多