Elvis Elvis - 29 days ago 12
jQuery Question

Sort json objects by priority then randomize everything els

Maybe someone can help. Can't figure out this by my self :(
I have list of json objects:

{"widget_foto": {"photos": [
{
"picThumb": "../../preview_stuff/img/widget-3-1.png",
"picOrig": "../../preview_stuff/img/widget-3-1.png",
"galeryUrl": "",
"shareUrl": "",
"priority": 0
},
{
"picThumb": "../../preview_stuff/img/widget-3-2.png",
"picOrig": "../../preview_stuff/img/widget-3-2.png",
"galeryUrl": "",
"shareUrl": "",
"priority": 2
},}}


I need to order objects by priority, what I have done already, but I can't figure out how to randomize objects that have priority 0 or if object priorities are equal.

Here's my code so far.

$(function(){
var url="../json/foto.json";
$.getJSON(url, function(json){
var fotoWidget = json.widget_foto;
var widget3 = ".col-widget-3" + " ";

//Populate content
var byPriority = fotoWidget.photos.slice(0);

byPriority.sort(function(a,b){
return b.priority - a.priority;
});
$.each(byPriority, function(index, value){
$(widget3 + ".widget-3-" + (index + 1)).css({"background-image": "url(images/" + value.picOrig + ")"});
});
});


Any help will be apriciated.

Answer

You can randomly shuffle the array first, then sort by priority.

var data = [
    {id:"0", "p":0},
    {id:"1", "p":0},
    {id:"2", "p":5},
    {id:"3", "p":5},
    {id:"4", "p":2},
    {id:"5", "p":2},
    {id:"6", "p":4},
    {id:"7", "p":4},
    {id:"8", "p":1},
    {id:"9", "p":1}
]
function shuffleArray(array) {
    for (var i = array.length - 1; i > 0; i--) {
        var j = Math.floor(Math.random() * (i + 1));
        var temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }
    return array;
}
shuffleArray(data)
data.sort( (a, b) => a.p - b.p )
JSON.stringify(data)
Comments