导航

萌即是正义!时不时分享一些ACG活动记录与有趣代码的小站!

JS根据列表排列对象数组

作者:广树·时间:2019-05-08 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}

侧边栏
最新评论
广树
2024-05-17
@老张博客:一千多人民币的水平吧
广树
2024-05-17
@MqyGalaxy:以前空中网的时代好像没有同步吧,现在同步了呀。
广树
2024-05-17
@DavidYR:不愧是大佬!行动力好强!我已经好几年没碰坦克世界了🤭
老张博客
2024-05-17
不知道你说的贵是多少钱呀。
MqyGalaxy
2024-05-17
@广树:我不是很清楚,一直都玩的是亚服美服OωO。但好像一直都是同步的吧
正在攻略

圣兽之王.jpg

传颂之物

PSN奖杯卡

PSN奖杯卡

赞助商广告