Help on Custom Array Sort

Hi,

can somebody please help me sort my custom array by share or cnt descending by any chance.

This is actually a product of a wixdata aggregate but since it cant sort based on count unlike SQL so I created an array. Now I want to sort according to the share/cnt column. this is for a leaderboard page passed through to a repeater. appreciate any help I can get.

Below is the custom array

0: “{"_id":"caafd397-13d7-8dfc-5574-99185e4c5431","profilename":"Mikel Mineque","cnt":1,"share":4}”
1: “{"_id":"727fa2f2-4714-acd6-89cb-07796f980b42","profilename":"Dennis Pagalan","cnt":7,"share":26}”
2: “{"_id":"c898285d-aebf-8e13-18eb-10fd95beac47","profilename":"J&C Accounting & Outsourcing Svcs.","cnt":1,"share":4}”
3: “{"_id":"ef158ec4-79a3-4806-afea-a67271b3f34f","profilename":"Ate Bita","cnt":9,"share":33}”
4: “{"_id":"bb61daca-31fb-d1f6-fdd6-96eecc40fa00","profilename":"Coach RJ","cnt":3,"share":11}”
5: “{"_id":"86a2ed6e-679b-a25a-ae7b-6e9e7db74368","profilename":"Rhian P Aseniero","cnt":2,"share":7}”
6: “{"_id":"225a15e3-438f-1c38-50e7-e662d35f8b80","profilename":"Marijon J Rafal","cnt":2,"share":7}”
7: “{"_id":"fb3038f1-57c9-d2ff-e0de-3e98951cf244","profilename":"Bita Mugot","cnt":2,"share":7}”

Hello,

If it is an array you can always loop through the array and use the sort() function to list out your values in descending order.

It may be easier to create a custom object instead, loop through your keys, push the values into a new array and then again use sort() to list out the array in descending order.

Here’s an example I made sorting out the id’s in descending order:

code

let customArray = {
 0: {"share": 4, "id":3},
 1: {"share": 2, "id":1},
 2: {"share": 8,"id":6},
 3: {"share": 3, "id":4},
 4: {"share": 1, "id":8},
};

let newArray = [];

for(let i in customArray){
 let id = customArray[i].id;
    newArray.push(id);
}

console.log(newArray.sort((a, b) => b - a));

result

There are a few other ways to accomplish this, you might want to look into using Object.keys and Object.values as well.

Hope this helped!

Best regards,

Thanks again for the help Miguel but I finally cracked it. below is the updated code

let customArray = {
 0: {"share": 4, "id":3},
 1: {"share": 2, "id":1},
 2: {"share": 8,"id":6},
 3: {"share": 3, "id":4},
 4: {"share": 1, "id":8},
};


let newArray = [];

for(let i in customArray){
 let id = customArray[i].id;
 let share = customArray[i].share;
 newArray.push(Object.assign({},{"share": share, "id":id}));

}

newArray.sort(function (a, b) {
 return b.share - a.share;
});

console.log(newArray);



Result: descending order by share with related id

0: "{\"share\":8,\"id\":6}"
1: "{\"share\":4,\"id\":3}"
2: "{\"share\":3,\"id\":4}"
3: "{\"share\":2,\"id\":1}"
4: "{\"share\":1,\"id\":8}"