Updated example, as it didn't match to the object structure which was given in the post
There is an array, which has multiple objects like this:
{
text: text,
elements: [
{
id: id,
page: pageNumber
}
]
}
Now I need to sort the content in two ways:
- Sort all array elements by the
text-field
I would do like this:
array.sort(function(a,b) {
if (a.text < b.text) return -1;
if (a.text > b.text) return 1;
return 0;
});
- The content of the nested
elements-array should also be sorted by thepage-field.
I don't know how to sort an array, which is nested in the objects... Unfortunately it gets more difficult as the elements are strings, but represent some page numbers. So how can I sort these data in a correct way, as elements could look like 123 or 23-34? And in the case 123-125, 23-34, the last element should be the first.
Example
[
{
text: 'Some text',
elements: [
{ id: 1, pages: '45-67' },
{ id: 2, pages: '12-34' }
]
},
{
text: 'Another text',
elements: [
{ id: 3, pages: '12-34' }
]
}
]
Should be sorted to:
[
{
text: 'Another text',
elements: [
{ id: 3, pages: '12-34' }
]
},
{
text: 'Some text',
elements: [
{ id: 2, pages: '12-34' },
{ id: 1, pages: '45-67' }
]
},
]
So the object order has changed, as A is before S and the order of the page elements in the (now) second object are ordered the other way round.