Lodash: order array of objects by boolean?
Asked Answered
H

3

10

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?

Hydromel answered 22/10, 2017 at 12:15 Comment(5)
It works fine - fiddleBigamy
Stupid me! There is something with my view layer then...Hydromel
Enjoy the view :)Bigamy
For anyone stumbling upon this question: be aware that because you're sorting a boolean, you're actually sorting 0 or 1. If you'd like the objects with 'true' to be on top, you should specify that it should sort desc (0/false is going to be on top otherwise).Huelva
@Erwin Lengkeek - i tried with 3 boolean fields - doesnt work - i think lodash cannot handle this situtaion :(Arsyvarsy
I
6

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));
Iloilo answered 11/6, 2020 at 8:49 Comment(2)
Can you explain what ES6 notation code does in your answer please ?Hurwitz
In ES6 notation we are creating a new array by concatenating 2 arrays. The first array has items filtered by accepted === false and the other array has items filtered by accepted === true. This will insert the accepted items in the last of the newly created array.Iloilo
G
2

@Erwin Lengkeek that worked for me, by sorting my booleanField descending, the Trues were on top.

this.sortableList = orderBy(this.sortableList, ['booleanField', 'stringField'], ['desc', 'asc']);
Galangal answered 23/8, 2022 at 0:41 Comment(0)
J
1

I've tried @Murtaza Mehmudji solution & it works fine!

const newArr = [
    ...myArr.filter(c => c.accepted === false),
    ...myArr.filter(c => c.accepted === true)
];
Joselow answered 22/8 at 17:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.