【问题标题】:Return array index where sub value is max with underscore.js使用 underscore.js 返回子值最大的数组索引
【发布时间】:2019-01-04 15:51:52
【问题描述】:

我有这样的设置:

docs[0]['edits'] = 1;
docs[1]['edits'] = 2;

我想获得编辑最多的docs[index]

使用下划线我可以获得适当的数组(即值docs[1]),但我仍然不知道与docs相关的实际索引。

_.max(docs, function(doc) { return doc['edits']; });

任何帮助将不胜感激。

【问题讨论】:

  • 是否使用下划线必需?没有库,这很容易
  • @CertainPerformance 不,但我在其他地方使用下划线,很高兴能充分利用图书馆。如果没有下划线,你会如何建议?
  • 同意@CertainPerformance 这在使用Array.indexOfArray.findIndex 的JS 中非常简单。下划线理想地意味着通过做它不做的事情来补充普通的 JS。这是普通的 JS 可以做的很好的事情。或者您可以执行其他选项以在一个循环而不是两个循环中执行查找和索引查找。
  • :-) 很公平。我只是喜欢下划线的优雅。不过会在下面给出@CertainPerformance 的代码。

标签: javascript arrays underscore.js


【解决方案1】:

要在没有库的情况下执行此操作,请遍历数组(可能使用 reduce),将迄今为止的最高数字和迄今为止的最高索引存储在变量中,当被迭代的项目较高时重新分配两者:

const edits = [
  3,
  4,
  5,
  0,
  0
];

let highestNum = edits[0];
const highestIndex = edits.reduce((highestIndexSoFar, num, i) => {
  if (num > highestNum) {
    highestNum = num;
    return i;
  }
  return highestIndexSoFar;
}, 0);

console.log(highestIndex);

另一种方式,使用findIndex,并将edits 传播到Math.max(代码更少,但需要迭代两次):

const edits = [
  3,
  4,
  5,
  0,
  0
];
const highest = Math.max(...edits);
const highestIndex = edits.indexOf(highest);

console.log(highestIndex);

【讨论】:

    【解决方案2】:

    只需使用maxBy

    const _ = require('lodash');
    
    const docs = [{'edits': 1}, {'edits': 2}, {'edits': 0}, {'edits': 4}, {'edits': 3}]
    
    const result = _.maxBy(docs, a => a.edits)
    
    console.log(result)
    

    https://repl.it/@NickMasters/DigitalUtterTechnologies

    纯JS方式

    const result2 = docs.reduce((result, { edits }) => edits > result ? edits : result, Number.MIN_SAFE_INTEGER)
    
    console.log(result2)
    

    【讨论】:

      猜你喜欢
      • 2012-07-03
      • 1970-01-01
      • 2021-08-17
      • 2021-06-09
      • 2019-09-11
      • 1970-01-01
      • 1970-01-01
      • 2021-07-09
      • 1970-01-01
      相关资源
      最近更新 更多