Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Find the highest number with same key from a multi dimensional array

I have this array :

data = {
  "lists": {
    "list-1": {
      "id": "list-1",
      "title": "list1",
      "cards": [
        {
          "id": "20",
          "title": "title"
        },
        {
          "id": "2",
          "title": "title"
        }
      ]
    },
    "list-2": {
      "id": "list-2",
      "title": "list2",
      "cards": [
        {
          "id": "4",
          "title": "title"
        },
        {
          "id": "3",
          "title": "title"
        }
      ]
    }
  }
}

I want to find the highest item with "id" as key. So here it would be "20"

I know how to do within an array but not from a multi dimensional array like here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const list = data.lists[listId]

>Solution :

const entryWithHighestID = 
  Object.entries(data.lists)          // from all the entries of data.lists
    .map(([key, { cards }]) => cards) // extract the cards property
    .flat()                           // flat to a single array
    .sort((a, b) => b.id - a.id)[0];  // sort by id descending, and get the first entry

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading