Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lodash: order array of objects by boolean?

I have an array of objects I'd like to order (essentially it's a table):

myArr = [{
    name: 'John',
    email: '[email protected]',
    accepted: true
}, {
    name: 'Alfred',
    email: '[email protected]',
    accepted: false
}]

I'm using orderBy from lodash like so:

//get columnName to sort by from another function
const newArr = _.orderBy(myArr, [columnName], ['asc'])

Ordering by name and email works fine, for accepted it doesn't do anything though. I understand I can store accepted as 0 and 1, but is there another way? Is lodash sufficient for that, or should I create a separate function for this?

like image 996
Runnick Avatar asked Oct 22 '17 12:10

Runnick


People also ask

How do you sort an array of objects in Lodash?

The _. sortBy() method creates an array of elements which is sorted in ascending order by the results of running each element in a collection through each iteratee. And also this method performs a stable sort which means it preserves the original sort order of equal elements.

Is Lodash sortBy stable?

Creates an array of elements, sorted in ascending order by the results of running each element in a collection thru each iteratee. This method performs a stable sort, that is, it preserves the original sort order of equal elements.

What is _ get?

The _. get() function is an inbuilt function in the Underscore. js library of JavaScript which is used to get the value at the path of object. If the resolved value is undefined, the defaultValue is returned in its place. Syntax: _.get(object, path, [defaultValue])


1 Answers

You can try this in ES6 Notation

const newArr = [
    ...myArr.filter(c => c.accepted === false),
    ...myArr.filter(c => c.accepted === true)
];

You can also use Array.sort Prototype

myArr.sort((a, b) => (a.accepted - b.accepted));
like image 97
Murtaza Mehmudji Avatar answered Oct 02 '22 01:10

Murtaza Mehmudji