1
Good evening, I’m having a difficult to sort array in javascript, the problem is that I need to sort it first by number of characters, ( Words with more characters appears first), I’ve done that, but after that I need to sort the words that have the same number of characters in alphabetical order but I can’t do it without disrespecting the first criterion.
follows My code :
var items = [
{ name: 'one', value: 3 },
{ name: 'three', value: 5 },
{ name: 'mond', value: 4 },
{ name: 'four', value: 4 },
{ name: 'ajdh', value: 4 },
{ name: 'at', value: 2 },
{ name: 'midnight', value: 8 }
];
items.sort(function (a, b) {
if (a.value > b.value) {
return -1;
}
if (a.value < b.value) {
return 1;
}
return 0;
});
items.sort(function (a, b) {
if (a.value == b.value) {
if (a.name > b.name) {
return -1;
}
if (a.name < b.name) {
return 1;
}
}
return 0;
});
console.log(items)
I need him to leave like this:
[ { name: 'midnight', value: 8 },
{ name: 'three', value: 5 },
{ name: 'ajdh', value: 4 },
{ name: 'four', value: 4 },
{ name: 'mond', value: 4 },
{ name: 'one', value: 3 },
{ name: 'at', value: 2 } ]
Note that when property value(Represents the number of characters) repeats with the same value the array needs to be in alphabetical order, but I don’t know how to do this without messing up the remaining order. Thank you
It worked, thank you very much!
– LEANDRO DA SILVA