1

Let's say I have a collection of documents. To make this simpler, let's say all these documents have just 2 fields, name and id, like below.

I want to get the document with the greatest value of "id". Can I use the .find({}) with some parameters? If so, I can't figure out which parameter would find me the max value of a certain field.

[
  {
    name: "name1",
    id: 1
  }
  {
    name: "name2",
    id: 2
  }
  {
    name: "name1",
    id: 3
  }
  {
    name: "name1",
    id: 0
  }
]
0

3 Answers 3

1

let documents = [
  {
    name: "name1",
    id: 1
  },
  {
    name: "name2",
    id: 2
  },
  {
    name: "name1",
    id: 3
  },
  {
    name: "name1",
    id: 0
  }
];

let max = documents.sort( (a, b) => a.id > b.id ? -1 : 1)[0]
console.log( max );

How about let maxIdDocument = documents.sort( (a, b) => a.id > b.id ? 1 : -1)[0]

1

First, sort in descending order, then get the first one:

const arr = [{
    name: "name1",
    id: 1
  },
  {
    name: "name2",
    id: 2
  },
  {
    name: "name1",
    id: 3
  },
  {
    name: "name1",
    id: 0
  }
];

const [greatest] = arr.sort(({ id: a }, { id: b }) => b - a);

console.log(greatest);

1

You can sort that array and with the function pop get the object with the greatest id.

arr.slice() // This is to avoid a mutation on the original array.

let arr = [   {     name: "name1",     id: 1   },   {     name: "name2",     id: 2   },   {     name: "name1",     id: 3   } ,  {     name: "name1",     id: 0   } ],
    greatest = arr.slice().sort(({id: a}, {id: b}) => a - b).pop();

console.log(greatest);
.as-console-wrapper { min-height: 100%; }

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.