javascript - 按顺序将数组排序到另一个数组
问题描述
我有两个数组:
主阵列:
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)
解决方案
-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; }
推荐阅读
- javascript - 带有多选下拉菜单的 JavaScript 过滤器元素
- java - org.springframework.beans.BeanInstantiationException ,无法使用 Oracle 数据源
- pandas - 为什么包含多列的熊猫数据框说 10 的维度为 2?
- c++ - bq.o:server.cpp:(.text+0x20):在 VS Code 2020 中编译 tcp/ip 程序时未定义对 `__imp_socket' 的引用
- angular - Angular - 对文本框的值更改执行过滤器
- c - 尝试从链表中删除时,我丢失了整个列表,而不仅仅是一个 int
- sharepoint - Sharepoint 查找列表
- r - 按字母数字和数字参数聚合列
- google-cloud-platform - 如何使用 cloudarmor 为我的 gke 入口配置 DDoS?
- java - 构建签名APK时android studio中的gradle问题