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.

4
  • is it a json string ? Commented Mar 20, 2014 at 12:03
  • @Andy That question is about sorting the properties in a single object, not sorting an array of objects. Commented Mar 20, 2014 at 12:04
  • stackoverflow.com/questions/1129216/… Commented Mar 20, 2014 at 12:04
  • Yeah. I noticed. Knew there was a duplicate somewhere tho. Commented Mar 20, 2014 at 12:05

3 Answers 3

2

You can use Array.sort()

array.sort(function(a, b) {
    return a.album < b.album;
});
Sign up to request clarification or add additional context in comments.

Comments

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/

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.