Je trie actuellement un tableau d'objets JSON par un nombre.
[
{ scorePriority: 10, scoreValue: "low" },
{ scorePriority: 3, scoreValue: "high" },
{ scorePriority: 10, scoreValue: "medium" }
]
Cela fonctionne bien, mais maintenant, je dois le trier par Elevé, Moyen, Faible et ignorer le nombre au total.
myArray.sort((a, b) => a.scorePriority - b.scorePriority)
J'ai besoin de trier par scoreValue, où il peut être faible, moyen ou élevé.
Avez-vous de l'aide?
3 Réponses :
Utilisez localeCompare pour trier alphabétiquement selon scoreValue:
const array = [
{ scoreValue: 'low', scorePriority: 0 },
{ scoreValue: 'medium', scorePriority: 5 },
{ scoreValue: 'low', scorePriority: 6 },
{ scoreValue: 'high', scorePriority: 2 },
{ scoreValue: 'medium', scorePriority: 0 },
{ scoreValue: 'high', scorePriority: 10 }
];
const sorted1 = [...array].sort((a, b) => a.scoreValue.localeCompare(b.scoreValue));
console.log(sorted1);
const sorted2 = [...array].sort((a, b) => {
const orders = { 'low': 0, 'medium': 1, 'high': 2 };
return orders[a.scoreValue] - orders[b.scoreValue];
});
console.log(sorted2); Ou, si vous voulez un ordre prédéfini (bas -> moyen -> élevé), utilisez une carte de classement dont les clés sont les les chaînes scoreValue possibles et dont les valeurs sont l'ordre associé pour ces clés:
array.sort((a, b) => {
const orders = { 'low': 0, 'medium': 1, 'high': 2 };
return orders[a.scoreValue] - orders[b.scoreValue];
});
array.sort((a, b) => a.scoreValue.localeCompare(b.scoreValue))
bien que vous n'ayez pas tort, j'ai trouvé la réponse de prasanth pour répondre à mes besoins plus facilement. apprécier ton aide!
Trier avec le premier tableau basé sur un index. Avec ordre DESC élevé à faible
var ind = ['high', 'medium', 'low'];
var arr = [{ scorePriority: 10, scoreValue: "low" }, { scorePriority: 10, scoreValue: "high" }]
arr = arr.sort((a,b) => {
return ind.indexOf(a.scoreValue) -ind.indexOf(b.scoreValue)
})
console.log(arr)
@vendu pour. toujours bienvenu
Si vous souhaitez utiliser lodash , vous pouvez procéder comme suit:
const items = [
{ scoreValue: 'low', scorePriority: 0 },
{ scoreValue: 'medium', scorePriority: 5 },
{ scoreValue: 'low', scorePriority: 6 },
{ scoreValue: 'high', scorePriority: 2 },
{ scoreValue: 'medium', scorePriority: 0 },
{ scoreValue: 'high', scorePriority: 10 }
];
_.sortBy(items, item => ["high", "medium", "low"].indexOf(item.scoreValue));