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!


Solution 1:

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();