2025年02月08日 建站教程
功能介绍:一个数组显示基础数据,一个数组显示排序顺序,让基础数据数组根据排序数组的顺序排序!
具体代码如下:
const data = [
{ id: 1, name: "web3" },
{ id: 2, name: "html5" },
{ id: 3, name: "css3" },
{ id: 4, name: "nodejs" },
{ id: 5, name: "vuejs" },
{ id: 6, name: "php" }
];
const order = [2, 4, 1, 6, 5, 3]; //根据这个顺序对id进行排序。也可以改成name
//方法
hash = {}
data.forEach(function(item) { hash[item.id] = item }) //id:根据需要修改成自己的参数
results = order.map(function(item) { return hash[item] })
//输出结果
console.log('输出结果:', results)
//输出结果:
//(6) [{…}, {…}, {…}, {…}, {…}, {…}]
//0: {id: 2, name: 'html5'}
//1: {id: 4, name: 'nodejs'}
//2: {id: 1, name: 'web3'}
//3: {id: 6, name: 'php'}
//4: {id: 5, name: 'vuejs'}
//5: {id: 3, name: 'css3'}
//length: 6
本文链接:http://so.lmcjl.com/news/22754/