最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

sorting - Define fixed sort order in JavaScript - Stack Overflow

programmeradmin3浏览0评论

I haven't found something in my research so I thought someone can help me here.

My problem is that I want to sort an array of objects which contains a status:

{
    "data":[
        {
            "status":"NEW"
        },
        {
            "status":"PREP"
        },
        {
            "status":"CLOS"
        },
        {
            "status":"END"
        },
        {
            "status":"ERR"
        },
        {
            "status":"PAUS"
        }
    ]
}

Now I want to set a fixed sort order like all objects with the status "END" ing first then all objects with the status "PREP" and so on.

Is there a way to do that in JavaScript?

Thanks in advance :)

I haven't found something in my research so I thought someone can help me here.

My problem is that I want to sort an array of objects which contains a status:

{
    "data":[
        {
            "status":"NEW"
        },
        {
            "status":"PREP"
        },
        {
            "status":"CLOS"
        },
        {
            "status":"END"
        },
        {
            "status":"ERR"
        },
        {
            "status":"PAUS"
        }
    ]
}

Now I want to set a fixed sort order like all objects with the status "END" ing first then all objects with the status "PREP" and so on.

Is there a way to do that in JavaScript?

Thanks in advance :)

Share Improve this question asked Jan 6, 2016 at 11:21 MarschiMarschi 631 silver badge6 bronze badges 3
  • Can you elaborate on what exactly you're trying to do? – Nick Zuber Commented Jan 6, 2016 at 11:24
  • Array.prototype.sort(). (The documentation says it all). – Ismael Miguel Commented Jan 6, 2016 at 11:24
  • try groupBy from underscoreJS. underscorejs/#groupBy OR try stackoverflow./questions/14592799/… – Vishal Rajole Commented Jan 6, 2016 at 11:27
Add a ment  | 

2 Answers 2

Reset to default 16

It's a pretty simple parison operation using a standard .sort() callback:

var preferredOrder = ['END', 'ERR', ..];
myArray.sort(function (a, b) {
    return preferredOrder.indexOf(a.status) - preferredOrder.indexOf(b.status);
});

You can use an object with their order values and sort it then.

var obj = { "data": [{ "status": "NEW" }, { "status": "PREP" }, { "status": "CLOS" }, { "status": "END" }, { "status": "ERR" }, { "status": "PAUS" }] };

obj.data.sort(function (a, b) {
    var ORDER = { END: 1, PREP: 2, PAUS: 3, CLOS: 4, ERR: 5, NEW: 6 };
    return (ORDER[a.status] || 0) - (ORDER[b.status] || 0);
});

document.write('<pre>' + JSON.stringify(obj, 0, 4) + '</pre>');

发布评论

评论列表(0)

  1. 暂无评论