【问题标题】:TypeScript: Sort Array 1 by indexOf value from Array 2TypeScript:按数组 2 中的 indexOf 值对数组 1 进行排序
【发布时间】:2020-05-07 23:54:40
【问题描述】:

我是 Typescript/JavaScript 的新手,所以我确定我错过了一些简单的东西。

我有一个包含 2 种类型的数组,每种类型都有一个包含 3 - 4 个名称的子数组:

myArray = [
{
    "type": "abc",
    "names": {
        "Jane Smith": 5,
        "John Doe": 3,
        "Jack Jones": 2
    }
},
{
    "type": "xyz",
    "names": {
        "Jane Smith": 3,
        "John Doe": 7,
        "Jack Jones": 3
    }
}
];

我需要知道哪个主要类型的总总数最高,并首先显示。在此示例中,“xyz”的总数最高((3 + 7 + 3) 与 (5 + 3 + 2))。所以我想在 abc 之前显示 xyz。

我成功地获得了两者的总数并将它们放入一个名为 totalValues 的新数组中:

totalValues = [
{
    "type": "xyz",
    "count": 13            
    }
},
{
    "type": "abc",    
    "count": 10            
    }
}
];

问题是我需要根据总数按类型对原始数组(myArray)进行排序,我无法弄清楚。

let sortedTotalValues = totalValues.sort().reverse();    //highest value first

let sortedGroupNames = null;

sortedGroupNames = myArray.sort((a, b) => {            
    return sortedTotalValues[0].indexOf(a) - sortedTotalValues[0].indexOf(b);
});

任何帮助将不胜感激。

【问题讨论】:

    标签: arrays angular typescript sorting


    【解决方案1】:
    const myArray = [
    {
        "type": "abc",
        "names": {
            "Jane Smith": 5,
            "John Doe": 3,
            "Jack Jones": 2
        }
    },
    {
        "type": "xyz",
        "names": {
            "Jane Smith": 3,
            "John Doe": 7,
            "Jack Jones": 3
        }
    }
    ];
    const sum =   (accumulator, currentValue) => accumulator + currentValue;
    
    const total = x=>Object.values(x.names).reduce(sum)
    
    console.log(myArray.sort((a,b)=>(total(b)-total(a))))
    [Codepen here][1]
    
    
      [1]: https://codepen.io/drGreen/pen/eYmbeze
    

    【讨论】:

      【解决方案2】:

      试试这个,

      let myArray = [
        {
          "type": "abc",
          "names": {
             "Jane Smith": 5,
             "John Doe": 3,
             "Jack Jones": 2
          }
        },
        {
          "type": "xyz",
          "names": {
             "Jane Smith": 3,
             "John Doe": 7,
             "Jack Jones": 3
          }
        }
      ];
      
      let modifiedArray = myArray.map(obj => {
        let total = 0;
        for (var property in obj.names) {
          total += obj.names[property];
        }
        return {
          ...obj,
          totalNamesValue: total // Added totalNamesValue which stores the total
        }
      });
      
      let sortedArray = modifiedArray.sort((a, b) => b.totalNamesValue - a.totalNamesValue)
      
      console.log(sortedArray);
      

      【讨论】:

        【解决方案3】:

        我猜如果您尝试首先使用findIndex() 找到基于type 属性的元素的索引,那么您可以将其推入最终数组中的正确位置。

        也许您可以尝试以下方法:

        const myArray = [{"type":"abc","names":{"Jane Smith":5,"John Doe":3,"Jack Jones":2}},{"type":"xyz","names":{"Jane Smith":3,"John Doe":7,"Jack Jones":3}}];
        
        const countsInOrder = myArray.map(({type, names}) => ({
          type,
          count: Object.entries(names).reduce((a, [k,v]) => a + v, 0)
        })).sort((a,b) => b.count - a.count);
        
        const result = new Array(myArray.length);
        
        myArray.forEach(e => {
          const index = countsInOrder.findIndex(a => a.type === e.type);
          result[index] = e;
        });
        
        console.log(result);

        希望对你有帮助!

        【讨论】:

          【解决方案4】:

          给定一个数组和一个排序标准,您可以简单地将您的标准作为函数输入到 .sort(...) 方法中。

          myArray = [
          {
              "type": "abc",
              "names": {
                  "Jane Smith": 5,
                  "John Doe": 3,
                  "Jack Jones": 2
              }
          },
          {
              "type": "xyz",
              "names": {
                  "Jane Smith": 3,
                  "John Doe": 7,
                  "Jack Jones": 3
              }
          }
          ];
          
          myArray.sort((a,b) => {
            let sumA = Object.values(a["names"]).reduce((total, curr) => total + curr, 0);
            let sumB = Object.values(b["names"]).reduce((total, curr) => total + curr, 0);
            
            return sumB -sumA;
          });
          
          console.log(myArray);

          注意:这确实有每次进行比较时重新计算总和的开销如下图

          myArray = [
          {
              "type": "abc",
              "names": {
                  "Jane Smith": 5,
                  "John Doe": 3,
                  "Jack Jones": 2
              }
          },
          {
              "type": "xyz",
              "names": {
                  "Jane Smith": 3,
                  "John Doe": 7,
                  "Jack Jones": 3
              }
          }
          ];
          
          let total = myArray.map( el => 
            Object.values(el["names"]).reduce((total, curr) => total + curr, 0));
            
          
          
          myArray.sort((a,b) => {
            let sumA = total[myArray.findIndex( el => el["type"] === a["type"] )];
            let sumB = total[myArray.findIndex( el => el["type"] === b["type"] )];
            
            return sumB - sumA;
          });
          
          console.log(myArray);

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2015-03-16
            • 2014-03-08
            • 2019-11-09
            • 1970-01-01
            • 2021-11-14
            • 1970-01-01
            • 1970-01-01
            • 2017-09-02
            相关资源
            最近更新 更多