JS sort object by "x" in the array

I am working on a small photo sharing site for my family photos (since we want to have full control over the images, the best local hosting). I designed it, working perfectly and want to add functionality.

right now all my images are being pulled from MySQL: ROW -> object objects into an array -> PHP -> JS array. the array looks like

var array = [{'key' = '1', 'title' = 'title', 'source' = 'path / to / image', 'album' = 'album}, ..]

inside the album tag it may have different album names and you want to re-sort the array bases on the albums, I did not think about how this works.

+4
source share
3 answers

you can use Array.sort()

array.sort(function(a, b) {
    return a.album < b.album;
});
+1
source
var array =  [
{'key' :  '1', 'title' :  'title', 'source' :  'path/to/image', 'album' :  'album1'},
{'key' :  '1', 'title' :  'title', 'source' :  'path/to/image', 'album' :  'album2'},
{'key' :  '1', 'title' :  'title', 'source' :  'path/to/image', 'album' :  'album3'},
{'key' :  '1', 'title' :  'title', 'source' :  'path/to/image', 'album' :  'album6'},
{'key' :  '1', 'title' :  'title', 'source' :  'path/to/image', 'album' :  'album5'},
{'key' :  '1', 'title' :  'title', 'source' :  'path/to/image', 'album' :  'album7'},
{'key' :  '1', 'title' :  'title', 'source' :  'path/to/image', 'album' :  'album6'}
];

array.sort(function(a,b){ return a.album > b.album;} );

console.log(array);

http://jsbin.com/xefujehe/1/

+1
source

Check out the MDN docs for Array.prototype.sort .

This method uses a comparison function. Here is an example:

function compare(a, b) {
  if (a is less than b by some ordering criterion)
     return -1;
  if (a is greater than b by the ordering criterion)
     return 1;
  // a must be equal to b
  return 0;
}

Here you can sort the album name:

var albums = [
{
    key: 110000,
    album: 'Starry nights'
}, {
    key: 100,
    album: 'Zebra kills Zebra'
}, {
    key: 1,
    album: 'Alfred Hitcock Presents'
}, {
    key: 50,
    album: 'baby whales'
}];

albums.sort(function(a, b){
    return a.album === b.album ? 0 : a.album > b.album;
});

console.log(albums);

jsFiddle .

Remember that when sorting, all uppercase letters appear before all lowercase letters.

+1
source

Source: https://habr.com/ru/post/1532656/


All Articles