I have an array for example this
javascript
[
{
"nombre": "nombre 1",
"score": 10
},
{
"nombre": "nombre 2",
"score": 10
},
{
"nombre": "nombre 3",
"score": 10
},
{
"nombre": "nombre 4",
"score": 10
},
{
"nombre": "nombre 19",
"score": 8
},
{
"nombre": "nombre 43",
"score": 6
},
{
"nombre": "nombre 87",
"score": 3
},
{
"nombre": "nombre 99",
"score": 1
}
]
Which I am ordering by score, using lodash like this:
_.orderBy(data, ['score'], ['desc'])
As you can see nombre 1
, nombre 2
, nombre 3
and nombre 4
have the same score, but when ordering it, nombre 1
it is always higher than nombre 2
, 3
and 4
, my idea is to order them by score, but those with the same score are not always in the same place
for instance
[
{
"nombre": "nombre 2",
"score": 10
},
{
"nombre": "nombre 3",
"score": 10
},
{
"nombre": "nombre 1",
"score": 10
},
{
"nombre": "nombre 4",
"score": 10
}
]
either
[
{
"nombre": "nombre 3",
"score": 10
},
{
"nombre": "nombre 1",
"score": 10
},
{
"nombre": "nombre 4",
"score": 10
},
{
"nombre": "nombre 2",
"score": 10
}
]
I don't know if I'm explaining myself well, but does anyone know how I can achieve this? My regards and thank you very much.
Thank you for such a good question, I have found a concrete but not generic way, it is the following:
This function returns the items ordered from highest score to lowest and in those with the same value, one randomly.
PS It could be improved by passing the name of the field by which you want to order