Skip to content

Instantly share code, notes, and snippets.

@gotraveltoworld
Created November 28, 2018 03:19
Show Gist options
  • Save gotraveltoworld/19f73f6036ffa4e5987b39ba3c9199a5 to your computer and use it in GitHub Desktop.
Save gotraveltoworld/19f73f6036ffa4e5987b39ba3c9199a5 to your computer and use it in GitHub Desktop.
How to use the JS array sort function to sort an array by text(convert to the int index).
// 根據預設排序列表順序的方式把文字轉換成排序的優先序
let positions = ['總經理', '副總', '部長', '主任', '員工'];
let staffs = [
{
'name': '員工1',
'position': '員工'
},
{
'name': '大明',
'position': '總經理'
},
{
'name': '副總1',
'position': '副總'
},
{
'name': '主任1',
'position': '主任'
},
{
'name': '部長1',
'position': '部長'
},
{
'name': '主任2',
'position': '主任'
},
{
'name': '員工2',
'position': '員工'
},
{
'name': '員工2',
'position': '員工'
},
{
'name': '員工3',
'position': '員工'
},
{
'name': '副總2',
'position': '副總'
},
{
'name': '部長2',
'position': '部長'
},
{
'name': '主任3',
'position': '主任'
},
{
'name': '主任4',
'position': '主任'
},
{
'name': '部長3',
'position': '部長'
},
];
// Sorting
staffs.sort((pre, after) => {
return positions.indexOf(pre.position) - positions.indexOf(after.position);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment