javascript - JS 将一个数组元素推到最后
问题描述
我正在尝试重新排列数组的排序。假设我有以下结构
const array = [{
location: 'Table 2',
data: {..}
}, {
location: 'Unassigned',
data: {..}
}, {
location: 'Table 1',
data: {..}
}
];
将“表 1”移动到索引 0、“表 2”紧随其后(对表 3、4 等保持相同的顺序)和“未分配”始终移动到最后的正确方法是什么。最好使用 lodash。
这是我到目前为止尝试过的
forEach(allItemsSorted, (item, index) => {
const total = allItemsSorted.length;
let hasUnassigned = false;
if (item.location === 'Unassigned') {
allItemsSorted[total] = item;
hasUnassigned = true;
}
if (hasUnassigned && index === total) {
return;
}
allItemsSorted[index] = item;
})
解决方案
您可以为所需订单获取一个对象,为未知值获取一个默认值,以将这些项目移动到数组的末尾。
const
array = [{ location: 'Table 2', data: {} }, { location: 'Unassigned', data: {} }, { location: 'Table 1', data: {} }],
order = { 'Table 1': 1, 'Table 2': 2, default: Infinity };
array.sort(({ location: a }, { location: b }) =>
(order[a] || order.default) - (order[b] || order.default));
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }
对于仅'Unassigned'
按升序排序到末尾和所有其他值,您也可以使用上面提到的 order 对象,但更改已知和未知字符串的值。
const
array = [{ location: 'Table 2', data: {} }, { location: 'Unassigned', data: {} }, { location: 'Table 1', data: {} }],
order = { Unassigned: 1 };
array.sort(({ location: a }, { location: b }) =>
(order[a] || 0) - (order[b] || 0) || a.localeCompare(b));
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }
推荐阅读
- c - Linux中chattr的替代方法
- c# - 使用异步与实体框架选择 IQueryable 类型的列表
- java - java,为什么会出现这些错误?--maven-compiler-plugin:3.7.0
- php - 从索引数组中删除一个元素
- r - 在不同时间间隔具有多个系列的 Dygraph
- google-cloud-endpoints - 在 Google Kubernetes Engine 上获取部署失败的 Google Endpoints
- java - 无法使用 Java 读取 XML 文档
- php - Laravel - GroupBy 作为别名
- apache-spark - Pyspark:java.lang.OutOfMemoryError:超出 GC 开销限制
- java - 使用 FirebaseAuthListener 如果没有用户登录,它将导航到带有片段的活动