I am trying to custom sort a JavaScript object but not able to get how we can do this in a right way. Say I am having an object like
var test = {
'yellow': [],
'green': [],
'red': [],
'blue': []
}
And I have an array with values of : var arr = ['red', 'green', 'blue', 'yellow'];
So after sorting, I want to output in the order which is specified in array like
var test = {
'red': [],
'green': [],
'blue': [],
'yellow': []
}
But for some reason, I am not able to achieve that. What am trying to do here is loop and sort but it sorts in A-Z pattern and not in the order I've specified the array in. Also, you might ask that am not even using my array in the sort function but am not getting an exact way to achieve this.
var test = {
'yellow': [],
'green': [],
'red': [],
'blue': []
}
var keys = Object.keys(test);
console.log(keys.sort()); //["blue", "green", "red", "yellow"] which is not ordered nor it's an object
Any directions will he helpful.
Note: I am having this specific requirement because am using HandleBars with default {{#each}}
block, but I want to loop the inner objects in that order. I can loop the objects in Handlebars and pass them to the template but than am not using the power of template engine. I want Handlebars to loop them or am I missing something? Is it fine if I loop the objects and pass the entire markup to handlebars template.