0

I have a setup like this:

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

I want to get the docs[index] of the one with the most edits.

Using Underscore I can get the appropriate array (ie the value docs[1]), but I still don't know the actual index in relation to docs.

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

Any help would be greatly appreciated.

6
  • 1
    Is using underscore required? This is very easy without a library Commented Jan 4, 2019 at 7:29
  • @CertainPerformance No, but I'm using Underscore elsewhere and it's nice to get the most out of the library. How would you suggest without Underscore? Commented Jan 4, 2019 at 7:32
  • Possible duplicate of find the array index of an object with a specific key value in underscore Commented Jan 4, 2019 at 7:33
  • Agreed with @CertainPerformance this is pretty trivial in JS using Array.indexOf or Array.findIndex. Underscore is ideally meant to compliment normal JS by doing things it doesn't. This is something plain JS can do just fine. Or you can do other options to do the find and index find in one loop instead of two. Commented Jan 4, 2019 at 7:34
  • :-) Fair enough. I just loved the elegance of underscore. Will give @CertainPerformance's code below a go though. Commented Jan 4, 2019 at 7:43

2 Answers 2

2

To do it without a library, iterate over the array (possibly with reduce), storing the highest number so far and the highest index so far in a variable, reassigning both when the item being iterated over is higher:

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);

Another way, with findIndex, and spreading the edits into Math.max (less code, but requires iterating twice):

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

console.log(highestIndex);

Sign up to request clarification or add additional context in comments.

Comments

1

Just use 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

Pure JS way

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

console.log(result2)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.