簡體   English   中英

根據另一個數組給定其內部值,對嵌套數組進行排序

[英]Sort a nested array, given its inner value, based on another array

我有 2 個 arrays,其中一個 (array1) 需要根據另一個 (array2) 根據其內鍵、角色進行排序。 我嘗試了不同的解決方案,但無法取得進一步進展,因為我不明白我應該采取什么步驟

我有以下 output:Array1

{
      "id":12,
      "roles":[
         {
            "id":12,
            "role":"team_player",
            "sub_role":null,
            "team_meta":{
               "default_player_role":{
                  "pos":null,
                  "role":"LWB"
               }
            }
         }
      ],
      "user_email":"w@w.w"
   },
   {
      "id":1575,
      "roles":[
         {
            "id":1672,
            "role":"team_player",
            "sub_role":null,
            "team_meta":{
               "default_player_role":{
                  "pos":null,
                  "role":"LB"
               }
            }
         }
      ],
      "user_email":"j@j.s"
   },
   {
      "id":1576,
      "roles":[
         {
            "id":1673,
            "role":"team_player",
            "sub_role":null,
            "team_meta":{
               "default_player_role":{
                  "pos":null,
                  "role":"CAM"
               }
            }
         }
      ],
      "user_email":"E@E.E",
   },

我想按照以下順序對上面的數組進行排序:

const array2 = ["LWB", "LB", "CAM"]

我遇到的問題是,在 array1 中排序應該根據的給定鍵太深,而且我還沒有找到任何方法來 map 來自第一個數組和 array2 的“角色”。

您需要獲取role並使用此值獲取訂單的索引。

 const getRole = ({ roles: [{ team_meta: { default_player_role: { role } }}] }) => role, data = [{ id: 1576, roles: [{ id: 1673, role: "team_player", sub_role: null, team_meta: { default_player_role: { pos: null, role: "CAM" } } }], user_email: "E@EE" }, { id: 12, roles: [{ id: 12, role: "team_player", sub_role: null, team_meta: { default_player_role: { pos: null, role: "LWB" } } }], user_email: "w@ww" }, { id: 1575, roles: [{ id: 1672, role: "team_player", sub_role: null, team_meta: { default_player_role: { pos: null, role: "LB" } } }], user_email: "j@js" }], order = ["LWB", "LB", "CAM"]; data.sort((a, b) => order.indexOf(getRole(a)) - order.indexOf(getRole(b))); console.log(data);
 .as-console-wrapper { max-height: 100%;important: top; 0; }

在幾個循環中,您也可以對其進行排序,但可能不是一個優雅的解決方案:

const nestedArray = [...]; // Replace Array 
const sortByArray = ["LWB", "LB", "CAM"];
const sortedArray = [];

sortByArray.forEach(function(sortByArrayValue) {
    nestedArray.forEach(function(nestedArrayValue) {
        nestedArrayValue.roles.forEach(function(role) {
            if (role.team_meta.default_player_role.role === sortByArrayValue) {
                sortedArray.push(nestedArrayValue);
            }
        });
    });
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM