【问题标题】:Determine potential index of an item if it were put into an array and sorted.如果将项目放入数组并排序,则确定项目的潜在索引。
【发布时间】:2017-07-11 15:21:20
【问题描述】:

能比克隆数组、推送项目和排序更快吗?

我有一个 array 的项目,还有一个不属于数组的 item

let array = [
  {name: 'Foo'},
  {name: 'Bar'},
  {name: 'Quux},
]

let item = {name: 'Baz'}

数组按字母顺序排序:

array = _.sortBy(array, 'name')

与原版 JS 相同:

function compare ({name: a}, {name: b}) {
  return (
    a < b ? -1 :
    a > b ?  1 :
             0
  )
}

array.sort(compare)

我的目标是弄清楚如果item 被推入array 并且array 以相同的方式再次排序,它将在哪个索引处结束。

一个明显的解决方案是尝试看看:

function getProposedItemIndex (array, item) {
  let tempArray = array.slice() // copy the array, we don't want to mutate the existing one
  tempArray.push(item)
  tempArray.sort(compare) // or `tempArray = _.sortBy(tempArray, 'name')`
  return tempArray.indexOf(item)
}

但这似乎不是最佳选择。

有没有办法在保持代码简洁易读的同时有效地做到这一点?没有难以理解的东西,比如for (let i; i&gt;array.length; i++) {}。一个 lodash 链将是理想的。

【问题讨论】:

  • 输入数组在添加新元素之前是否已经排序?然后你需要做的就是遍历现有数组,并检查你的新项目何时变得比当前的“更大”,此时你可以跳出循环......

标签: javascript arrays sorting ecmascript-6 lodash


【解决方案1】:
var index=0;
while(compare(array[index],item)>0) index++;
if(index===array.length) index=-1;

在行动:

let array = [
  {name: 'Foo'},
  {name: 'Bar'},
  {name: 'Quux'},
].sort(compare);

let item = {name: 'Baz'};

function compare ({name: a}, {name: b}) {
  return (
    a < b ? -1 :
    a > b ?  1 :
             0
  )
}

var index=0;
while(compare(array[index],item)>0) index++;
if(index===array.length) index=-1;
console.log(index);

【讨论】:

  • 不错!这依赖于数组已经排序的想法,对吧?这个条件可以工作吗:array[index].name &gt; item.name,以防我使用 lodash 进行排序并且手头没有compare
  • @lolmaus 是的。 no while(array[index].name
  • 恭喜获得 10K。本来希望对你达到 10K 负责,但 StackOverflow 延迟了我的赏金。
【解决方案2】:

假设array已经排序,那么我们可以使用lodash#sortedIndexBy来获取索引。

var index = _.sortedIndexBy(array, item, 'name');

let array = [
  {name: 'Bar'},
  {name: 'Foo'},
  {name: 'Quux'},
];

let item = {name: 'Baz'};

var index = _.sortedIndexBy(array, item, 'name');

console.log(index);
&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"&gt;&lt;/script&gt;

【讨论】:

    猜你喜欢
    • 2013-11-28
    • 2012-03-25
    • 2019-11-23
    • 2022-01-10
    • 1970-01-01
    • 2020-09-05
    • 2012-07-02
    • 1970-01-01
    • 2013-11-24
    相关资源
    最近更新 更多