4

I have been working on a small social photo sharing site for my family photos (as we want to have complete control over the images, local hosting is best). I have developed it working perfectly and want to add functionality.

right now all my images are pulled from MySQL: ROW -> object objects into 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 could have different album names and want to re-sort the array bases on the albums, I have not thought of a way that works.

Drew
  • 1,171
  • 4
  • 21
  • 36

3 Answers3

2

You can use Array.sort()

array.sort(function(a, b) {
    return a.album < b.album;
});
techfoobar
  • 65,616
  • 14
  • 114
  • 135
1
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/

Vasiliy vvscode Vanchuk
  • 7,007
  • 2
  • 21
  • 44
1

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

This method takes a comparison function. Here's 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's how you'd sort on 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.

Be aware while sorting that all capital letters come before all lowercase letters

Joseph Yaduvanshi
  • 20,241
  • 5
  • 61
  • 69