基于另一个数组的值的打字稿顺序数组

时间:2019-10-29 17:43:19

标签: javascript typescript

让我说我有一个基本数组

let object2 = ["DotNet", "ETL", "Hadoop", "Java", "Oracle", "Pega", "MainFrame"]

我想按基本数组的相同顺序对第二个数组进行排序

 let object1 = [{Name: "Java", ResourceCount: 3}, {Name: "DotNet", ResourceCount: 4}, {Name: "Hadoop", ResourceCount: 1}, {Name: "Pega", ResourceCount: 2}, {Name: "Oracle", ResourceCount: 1}, {Name: "ETL", ResourceCount: 1}, {Name: "MainFrame", ResourceCount: 0}]

所以看起来像这样

object1 = 
[{Name: "DotNet", ResourceCount: 4},
{Name: "ETL", ResourceCount: 1},
{Name: "Hadoop", ResourceCount: 1},
{Name: "Java", ResourceCount: 3}, 
{Name: "Oracle", ResourceCount: 1},
{Name: "Pega", ResourceCount: 2},
{Name: "MainFrame", ResourceCount: 0}]

没有硬编码怎么办?

2 个答案:

答案 0 :(得分:1)

一种可能的解决方案是使用Array.map来迭代您的顺序名称列表-并将每个String“映射”到对象列表中的相关对象中。

使用Array.find完成关联,该const list1 = ["DotNet", "ETL", "Hadoop", "Java", "Oracle", "Pega", "MainFrame"]; const list2 = [{Name: "Java", ResourceCount: 3}, {Name: "DotNet", ResourceCount: 4}, {Name: "Hadoop", ResourceCount: 1}, {Name: "Pega", ResourceCount: 2}, {Name: "Oracle", ResourceCount: 1}, {Name: "ETL", ResourceCount: 1}, {Name: "MainFrame", ResourceCount: 0}]; const ordered = list1.map(function(nameValue) { return list2.find((obj) => (obj.Name === nameValue)); }); console.log(ordered);接收返回相关对象的函数作为参数:

{{1}}

答案 1 :(得分:0)

let object2 = ["DotNet", "ETL", "Hadoop", "Java", "Oracle", "Pega", "Mainframe"]
let object1 = [{Name: "Java", ResourceCount: 3}, {Name: "DotNet", ResourceCount: 4}, {Name: "Hadoop", ResourceCount: 1}, {Name: "Pega", ResourceCount: 2}, {Name: "Oracle", ResourceCount: 1}, {Name: "ETL", ResourceCount: 1}, {Name: "Mainframe", ResourceCount: 0}]
var arr=[]

object2.map(item=>{
  object1.map(data=>{
    if(data.Name===item)
         {
           arr.push(data)
         }          
                    })
})
console.log(arr)