首页 > 解决方案 > 按顺序将数组排序到另一个数组

问题描述

我有两个数组:

主阵列:

const items = [
  "Лопата 123",
  "Empty Forest",
  "Forever young",
  "My ears",
  "Most Important",
  "16 Tons",
  "Operation Flashpoint",
  "Prize A1",
  "Нарешті літо",
];

和键数组:

const keys = ["Prize A1", "Forever young", "Most Important"];

我想按照键数组的顺序对第一个数组进行排序,例如:

const expected = [
  "Prize A1",
  "Forever young",
  "Most Important",
  "Лопата 123",
  "Empty Forest",
  "My ears",
  "16 Tons",
  "Operation Flashpoint",
  "Нарешті літо",
]

我写了一些代码,但它不能正常工作:

const expectedOrder = items.sort(function(a, b) {
   return keys.indexOf(b) - keys.indexOf(a);
});

 const items = [
    "Лопата 123",
    "Empty Forest",
    "Forever young",
    "My ears",
    "Most Important",
    "16 Tons",
    "Operation Flashpoint",
    "Prize A1",
    "Нарешті літо",
  ];
    
const keys = ["Prize A1", "Forever young", "Most Important"];

const expectedOrder = items.sort(function(a, b) {
   return keys.indexOf(b) - keys.indexOf(a);
});

console.log('expectedOrder', expectedOrder)

标签: javascriptarrayssorting

解决方案


-1您可以使用索引的默认值进行排序。

 const
     items = ["Лопата 123", "Empty Forest", "Forever young", "My ears", "Most Important", "16 Tons", "Operation Flashpoint", "Prize A1", "Нарешті літо"],
     keys = ["Prize A1", "Forever young", "Most Important"];

items.sort((a, b) => ((keys.indexOf(a) + 1) || Number.MAX_VALUE) - ((keys.indexOf(b) + 1) || Number.MAX_VALUE));

console.log(items);
.as-console-wrapper { max-height: 100% !important; top: 0; }

一个更短的方法是使用一个默认值对对象进行排序。

 const
     items = ["Лопата 123", "Empty Forest", "Forever young", "My ears", "Most Important", "16 Tons", "Operation Flashpoint", "Prize A1", "Нарешті літо"],
     order = { "Prize A1": 1, "Forever young": 2, "Most Important": 3, default: Number.MAX_VALUE };

items.sort((a, b) => (order[a] || order.default) - (order[b] || order.default));

console.log(items);
.as-console-wrapper { max-height: 100% !important; top: 0; }


推荐阅读