Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

339
Vistas
Lodash sortby first condition and then check for other conditions

I am using lodash to sort by value in a function. It is sorting by value at the moment. However, I would like to add another condition. I want to make it so that it sorts by this condition first(meaning a filed will be equal to something), then it will do the sorting by value.

In other words, there is one item that has the name of 'Sally'. This item should be first, and then the rest of the items are sorted by value.

I have been doing many research on this and could not find anything online. Wondering if anyone has ever come across this issue. Please see my code:

const sortByNameThenValue = () => {
  let result;
  
  result = sortBy(name, 'Sally') && sortBy(allowance, 'value').reverse();
}

I was also thinking of chaining it but doesnt seem to work as well. Please let me know if you see something. Thanks and appreciate it!

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

You can do this in lodash:

const sorted = _.sortBy(
  people, 
  [(person) => person.name !== 'Sally', (person) => person.value]
);

sortBy takes an array of elements and an array of functions, and "[sort] in ascending order by the results of running each element in a collection thru each iteratee"

Here is also a sandbox for demo

Sort in reverse order:

const sorted = _.sortBy(people, [
  (person) => person.name === "Sally",
  (person) => person.value
]).reverse();
about 4 years ago · Juan Pablo Isaza Denunciar

0

You did not supply any sample data, so I just made up some stuff. There is no need to include the lowdash library, as sorting is already available in Vanilla-JS.

const arr=[{name:"Fred",value:138},{name:"Harry",value:5},{name:"Sally",value:34},{name:"Andy",value:257},{name:"Sue",value:142},{name:"Peggy",value:33},{name:"Frank",value:85}];

function val(o){
 return o.value+(o.name==="Sally"?1e50:0)
}

console.log(arr.sort((a,b)=>
  val(b)-val(a)));

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda