具有特定关键字/字符串的排序数组

时间:2019-02-26 15:46:24

标签: javascript typescript

我正在处理逻辑框架,我想按此顺序对数组进行排序

  • 影响
  • 结果
  • 输出
  • 活动

我有这样的数组

{ id : 15 , parentId : 18 , type : OUTPUT , sequence : 1 },
{ id : 16 , parentId : 15 , type : OUTCOME , sequence : 1 },
{ id : 18 , parentId : null , type : IMPACT , sequence : 1 },
{ id : 14 , parentId : null , type : IMPACT , sequence : 2 },
{ id : 17 , parentId : 14, type : OUTCOME , sequence : 1 },

这是来自数据库的原始数据,并通过序列进行排序

我想用所有“ IMPACT”类型对它进行排序,使其在数组上排第一,依此类推...

{ id : 18 , parentId : null , type : IMPACT , sequence : 1 },
{ id : 14 , parentId : null , type : IMPACT , sequence : 2 },
{ id : 16 , parentId : 15 , type : OUTCOME , sequence : 1 },
{ id : 17 , parentId : 14, type : OUTCOME , sequence : 2 },
{ id : 15 , parentId : 18 , type : OUTPUT , sequence : 1 },

1 个答案:

答案 0 :(得分:0)

看看Array.sort,并将您自己的自定义比较函数传递给它:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

例如,类似这样的方法应该起作用:

arrayFromDatabase.sort(function(a, b) {
    if (a.type === IMPACT && b.type !== IMPACT) {
        return -1;
    } else if (a.type !== IMPACT && b.type === IMPACT) {
        return 1;
    } else {
        return a.sequence - b.sequence;
    }
});

请注意,为简洁起见,我将您提到的其他类型留给读者作为练习。

相关问题