Is there a way to partially sort an array in JavaScript based on specific conditions I choose?
Let's say we have an array:
var tab = [
{html: 'This is a test'},
{html: 'Locked item', locked: true},
{html: 'Another item'},
{html: 'Another one'}
//and many more items...
];
In this array, the 2nd item is marked as "locked" and should remain at the same position (2nd place) after sorting:
var tab = [
{html: 'Another item'},
{html: 'Locked item', locked: true},
{html: 'Another one'},
{html: 'This is a test'},
//and many more items...
];
This is the current code snippet that needs modification:
var tab = [
{html: 'This is a test'},
{html: 'Locked item', locked: true},
{html: 'Another item'},
{html: 'Another one'}
//and more items...
];
tab.sort(function(a,b){
var aVal = a.html.toLowerCase();
var bVal = b.html.toLowerCase();
if (aVal===bVal)
return 0;
else
return aVal < bVal ? -1 : 1;
//how can we handle locked items here?
});
//desired output:
/*var tab = [
{html: 'Another item'},
{html: 'Locked item', locked: true},
{html: 'Another one'},
{html: 'This is a test'},
//and more items...
];*/
console.log(tab);
For reference, you can check the fiddle.