从多维数组中查找具有相同键的最大数字

问题描述 投票:0回答:1

我有这个数组:

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"
        }
      ]
    }
  }
}

我想找到以“id”为键的最高项。所以这里是“20”

我知道如何在数组中执行操作,但不知道如何在像这里这样的多维数组中执行操作

const list = data.lists[listId]
javascript sorting multidimensional-array
1个回答
1
投票
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

© www.soinside.com 2019 - 2024. All rights reserved.