导航

萌即是正义!时不时分享一些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-08
@Asuna:谢谢!谢谢!
Asuna
2024-05-08
恭喜获得高质量博客认证~
广树
2024-05-08
@老张博客:是的,不仅仅是大城市,很多小乡村也是依靠动漫发展起来的旅游产业,所以不要小看文化产业带来的经济价值啊!
老张博客
2024-05-08
到日本 是不是大街小巷都是这些动漫呀!
广树
2024-05-08
@Chise Hachiroku:不是还有,而是最近出来的新服务🤭。送货时间太迟了,不是急需的话还是一般配送比较好。
正在攻略

圣兽之王.jpg

传颂之物

PSN奖杯卡

PSN奖杯卡

赞助商广告