I have a very simple arrangement of objects, something like this:
let profiles = [
{
'title': 'X',
'url' : 'https://google.com',
'description': 'Lorem'
},
{
'title': 'Y',
'description': 'Ipsum'
}
];
Each object has the properties title
and description
, but optionally has url
.
I make a sort
to the arrangement to sort it in alphabetical order according to title
.
profiles.sort( (a, b) => {
return a.title.toLowerCase() > b.title.toLowerCase();
});
And at the end I insert the data of the fix in the HTML with a forEach
:
profiles.forEach( (profile) => {
let element = '<tr><td>${profile.title}</td><td>${profile.description}</td></tr>';
if ( profile.url !== undefined ) {
element = '<tr><td>${profile.title}</td><td><a href="${profile.url}" target="_blank">${profile.description}</a></td></tr>';
}
document.getElementsByTagName('tbody')[0].insertAdjacentHTML('beforeend', element);
});
This works well, the problem is that when I get to the 11 elements of the arrangement it does not order it correctly. Example:
I should get this:
Age
Digimon
Github
Hobbies
Job
MAL
Name
OS
Steam
Twitter
Type
But I get this:
Job
OS
Github
Digimon
Name
MAL
Hobbies
Age
Steam
Twitter
Type
So far I have tried to put both the declaration of the array and the sort within a function that returns a promise, and then use the then
of that promise and thus insert in the HTML, but it worked exactly the same. It looked something like this:
let ordenar = () => {
return new Promise( (resolve, reject) => {
let profiles = [
{..},{..}
];
profiles.sort( (a, b) => {
return a.title.toLowerCase() > b.title.toLowerCase();
});
resolve(profiles);
});
}
ordenar().then(resp => {
resp.forEach( (profile) => {
....
});
}).catch();