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?
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.
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.
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])
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With