javascript - 使用另一个数组对对象数组进行排序
问题描述
我有一个像这样的对象数组,想用另一个对象数组重新排序。我曾尝试使用 indexOf 但可能会混淆我的语法,因为数组无法重新排序。我已经阅读了类似的问题,但无法将这些解决方案应用于我的问题。这是代码:
const task = [
{'title':1.1 , 'description': 'task description here' },
{'title':1.2 , 'description': 'task description here' },
{'title':1.3 , 'description': 'task description here' },
{'title':1.4 , 'description': 'task description here' }
];
var taskSort = [
{'title':1.2 },
{'title':1.4 },
{'title':1.3 },
{'title':1.1 }
];
task.sort(function(a, b) {
return taskSort.indexOf(a.title) - taskSort.indexOf(b.title); \\have tried many variations of this line
});
console.clear();
console.log(task);
提前谢谢了!
解决方案
基本上,您不是对值进行排序,而是根据另一个数组中指定的顺序重新排列它们
因此,您不能使用该Array.prototype.sort
逻辑,但可以执行以下操作
var taskSort = [
{'title':1.2 },
{'title':1.4 },
{'title':1.3 },
{'title':1.1 }
];
var task = [
{'title':1.1 , 'description': 'task description here' },
{'title':1.2 , 'description': 'task description here' },
{'title':1.3 , 'description': 'task description here' },
{'title':1.4 , 'description': 'task description here' }
];
var sortedTask = taskSort.map(tS => task.find(t => t.title === tS.title))
console.log(sortedTask);
本质上,您正在映射 taskSort 数组并创建一个新数组,其中的值满足 taskSort 数组中的值标记的条件
推荐阅读
- function - Solidity 编程
- parquet - 我可以通过索引访问 Parquet 文件而不将整个文件读入内存吗?
- java - 小时候可以“收养”一个班级吗?
- ubuntu - 我可以通过 Ubuntu 的 nmcli 工具登录我的 VPN,从终端传递用户名和密码吗?
- maven - Maven Artefacts - 为什么要使用 PGP 签名和 md5/sha1 哈希?
- python - 操作数据集
- javascript - 将自定义事件绑定到动态创建的元素
- python - 尝试运行“pytest --html=pytest_report.html”时,Circleci 不适用于我的 config.yml 文件,产生错误“没有这样的选项:--html”
- reactjs - Mongoose NextJS OverwriteModelError:编译后无法覆盖`Note`模型
- javascript - 如何使输入转到该文件