简体   繁体   中英

Sort on basis of given order in javaScript

I have array of object like :

var array = [
    { id: 1, color: red,    value: 1 },
    { id: 2, color: red,    value: 2 },
    { id: 3, color: yellow, value: 3 },
    { id: 4, color: yellow, value: 4 },
    { id: 5, color: green,  value: 4 }
];

I want sorted order where green -> yellow -> red

after array.sort(custmeSort()) output should be

[
    { id: 5, color: green,  value: 4 },   
    { id: 3, color: yellow, value: 3 },
    { id: 4, color: yellow, value: 4 },
    { id: 1, color: red,    value: 1 },
    { id: 2, color: red,    value: 2 }
]

How to achive this in javascript.

You can use one object to set sorting order, and then just use sort()

 var array = [ {id: 1, color: 'red',value: 1}, {id: 2, color: 'red',value: 2}, {id: 3, color: 'yellow',value: 3}, {id: 4, color: 'yellow',value: 4}, {id: 5, color: 'green',value: 4}, ] var order = { green: 1, yellow: 2, red: 3 } var result = array.sort(function(a, b) { return order[a.color] - order[b.color]; }) console.log(result) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM