代码之家  ›  专栏  ›  技术社区  ›  Mathieu

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

  •  0
  • Mathieu  · 技术社区  · 2 年前

    我有这个数组:

    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]
    
    3 回复  |  直到 2 年前
        1
  •  1
  •   moonwave99    2 年前
    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
    
    
        2
  •  1
  •   Alexander Nenashev    2 年前

    将列表减少到卡ID的最小值:

    const max = Object.keys(data.lists).reduce((r, key) => data.lists[key].cards.forEach(card => +card.id > r.id && (r = card)) || r, {id: -1});
    console.log(max);
    <script>
    const 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"}]}}};
    </script>

    如果您想要最大速度,只需循环:

    let max = {id: -1};
    
    for(const key in data.lists){
      const cards = data.lists[key].cards;
      for(let i = 0; i < cards.length; i++){
        const card = cards[i];
        if(+card.id > max.id) max = card;
      }
    }
    console.log(max);
    <脚本>
    const 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;
    </脚本>
    ` Chrome/117
    ----------------------------------------------------------------------------
    Alexander fast looping           1.0x  |  x10000000  334  343  344  345  358
    pilchard's tweak to one-liner    1.2x  |  x10000000  397  400  405  407  410
    Alexander one-liner              1.3x  |  x10000000  424  427  429  429  432
    moonwave99                      15.3x  |   x1000000  512  512  513  519  521
    ----------------------------------------------------------------------------
    https://github.com/silentmantra/benchmark `
    

    const 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"}]}}};
    
    // @benchmark moonwave99
    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];
    
    // @benchmark pilchard's tweak to one-liner
    Object.keys(data.lists).reduce((r, key) => data.lists[key].cards.reduce((c, card) => +card.id > c.id ? card : c, r), {id: -1});
    
    // @benchmark Alexander one-liner
    Object.keys(data.lists).reduce((r, key) => data.lists[key].cards.forEach(card => +card.id > r.id && (r = card)) || r, {id: -1});
    
    // @benchmark Alexander fast looping
    let max = {id: -1};
    
    for(const key in data.lists){
      const cards = data.lists[key].cards;
      for(let i = 0; i < cards.length; i++){
        const card = cards[i];
        if(+card.id > max.id) max = card;
      }
    }
    max;
    
    /*@end*/eval(atob('e2xldCBlPWRvY3VtZW50LmJvZHkucXVlcnlTZWxlY3Rvcigic2NyaXB0Iik7aWYoIWUubWF0Y2hlcygiW2JlbmNobWFya10iKSl7bGV0IHQ9ZG9jdW1lbnQuY3JlYXRlRWxlbWVudCgic2NyaXB0Iik7dC5zcmM9Imh0dHBzOi8vY2RuLmpzZGVsaXZyLm5ldC9naC9zaWxlbnRtYW50cmEvYmVuY2htYXJrL2xvYWRlci5qcyIsdC5kZWZlcj0hMCxkb2N1bWVudC5oZWFkLmFwcGVuZENoaWxkKHQpfX0='));
        3
  •  0
  •   BGPHiJACK    2 年前

    您可以通过迭代嵌套结构并跟踪找到的最高值,从给定的多维数组中找到具有“id”键的最高项。这里有一个JavaScript函数可以实现这一点:

    最有效的方法:120OP/s

    const 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"
            }
          ]
        }
      }
    };
    function findHighestId(data) {
      let highestId = -1;
    
      for (const listKey in data.lists) {
        const list = data.lists[listKey];
    
        for (const card of list.cards) {
          const cardId = parseInt(card.id, 10);
    
          if (!isNaN(cardId) && cardId > highestId) {
            highestId = cardId;
          }
        }
      }
    
      return highestId;
    }
    
    const highestId = findHighestId(data);
    console.log("Highest ID:", highestId); // Output: Highest ID: 20

    另一种编写方式:86K OP/s

    const 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"
            }
          ]
        }
      }
    };
    
    function findHighestId(data) {
      return Object.values(data.lists)
        .flatMap(list => list.cards)
        .map(card => parseInt(card.id))
        .filter(id => !isNaN(id))
        .reduce((highestId, currentId) => Math.max(highestId, currentId), -1);
    }
    
    const highestId = findHighestId(data);
    console.log("Highest ID:", highestId); // Output: Highest ID: 20

    最后一次尝试。。。这可以通过多种方式实现:86K OP/s

    const 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"
            }
          ]
        }
      }
    };
    
    
    const highestId = Object.values(data.lists)
      .flatMap(list => list.cards)
      .reduce((highest, card) => {
        const cardId = parseInt(card.id);
        return cardId > highest ? cardId : highest;
      }, -1);
    
    console.log("Highest ID:", highestId);
        4
  •  0
  •   Slai    2 年前

    这个 JSON.parse reviver JSON.stringify replacer 可用于处理嵌套值:

    const 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" } ]
        }
      }
    }
    
    let max = 0
    JSON.stringify(data, (k, v) => (max = Math.max(max, v) || max, v))
    
    console.log( max )