JS根据列表排列对象数组
作者:广树 | 时间:2019-5-8 09:39:51 | 分类 : JavaScript/jQuery/Vue
应用场景:将对象数组根据指派的数组内容进行排序,未指定的对象按照原始顺序。
- const nodeData_ = [
- {account:'a',node:1},
- {account:'b',node:2},
- {account:'c',node:3},
- {account:'d',node:4},
- {account:'e',node:5},
- {account:'f',node:6}
- ]
- const sortInfo = ['f','c','b']
- nodeData_.sort((a, b) => {
- if (sortInfo.indexOf(a.account) === -1 && sortInfo.indexOf(b.account) === -1) {
- return 1
- } else if (sortInfo.indexOf(a.account) !== -1 && sortInfo.indexOf(b.account) === -1) {
- return -1
- } else if (sortInfo.indexOf(a.account) === -1 && sortInfo.indexOf(b.account) !== -1) {
- return 1
- }
- return sortInfo.indexOf(a.account) - sortInfo.indexOf(b.account)
- })
- 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}
赞一个2
发表评论: