Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

337
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!