应用场景:将对象数组根据指派的数组内容进行排序,未指定的对象按照原始顺序。

  1. const nodeData_ = [
  2. {account:'a',node:1},
  3. {account:'b',node:2},
  4. {account:'c',node:3},
  5. {account:'d',node:4},
  6. {account:'e',node:5},
  7. {account:'f',node:6}
  8. ]
  9. const sortInfo = ['f','c','b']
  10. nodeData_.sort((a, b) => {
  11. if (sortInfo.indexOf(a.account) === -1 && sortInfo.indexOf(b.account) === -1) {
  12. return 1
  13. } else if (sortInfo.indexOf(a.account) !== -1 && sortInfo.indexOf(b.account) === -1) {
  14. return -1
  15. } else if (sortInfo.indexOf(a.account) === -1 && sortInfo.indexOf(b.account) !== -1) {
  16. return 1
  17. }
  18. return sortInfo.indexOf(a.account) - sortInfo.indexOf(b.account)
  19. })
  20. console.log(nodeData_)

输出结果:

0: {account: "f", node: 6}
1: {account: "c", node: 3}
2: {account: "b", node: 2}
3: {account: "a", node: 1}
4: {account: "d", node: 4}
5: {account: "e", node: 5}