4

I've tried to search something similar to what I want but i haven't find it so here i am.

I'm going to post a practical example, so you guys can help me.

I'm building this app in Javascript that has a BJJ belt system. So the data I have is something similar to:

belts = [{
    color: 'white',
    stripes:2,
    date: '0000000000' // timestamp
},{
    color: 'blue',
    stripes:1,
    date: '0000000000' // timestamp
},{
    color: 'purple',
    stripes:0,
    date: '0000000000' // timestamp
},{
    color: 'purple',
    stripes:1,
    date: '0000000000' // timestamp
},{
    color: 'white',
    stripes:3,
    date: '0000000000' // timestamp
},{
    color: 'white',
    stripes:4,
    date: '0000000000' // timestamp
},{
    color: 'brown',
    stripes:1,
    date: '0000000000' // timestamp
},{
    color: 'black',
    stripes:0,
    date: '0000000000' // timestamp
}];

So now I want to sort it by belt AND stripes.

So I want to create a rule with the order of the belts that needs to be sorted.

Something like:

belt_rules = ['white','blue','purple','brown', 'black'];

And when i run the sort, i will have my array that before was all unsorted, to display in order of the above rules and its ascending stripes.

I have no clue of how i would do that. Anyone up to the challenge and can help me?

Thanks

Rafael
  • 1,295
  • 14
  • 21

2 Answers2

4
belts.sort(function(a, b) {
    var acolor = belt_rules.indexOf(a.color);
    var bcolor = belt_rules.indexOf(b.color);
    var color_diff = acolor - bcolor;
    return color_diff || a.stripes - b.stripes;
});
Barmar
  • 741,623
  • 53
  • 500
  • 612
0
var ordering = {}, // map for efficient lookup of sortIndex
    sortOrder = ['fruit','candy','vegetable'];
for (var i=0; i<belt_rules.length; i++)
    ordering[belt_rules[i]] = i;

belts.sort( function(a, b) {
    return (ordering[a.type] - ordering[b.type]) || a.stripes - b.stripes;
});
Bergi
  • 630,263
  • 148
  • 957
  • 1,375