How to sort the objects with select #1757
Answered
by
markwhitfeld
bhagavan44
asked this question in
Q&A
-
Hello All, I need help with sorting of objects with selector. I have following 2 selectors, where the 1st with out sort is working fine, 2nd one with sort is not working. Can anybody tell me what I am doing wrong in here?
|
Beta Was this translation helpful? Give feedback.
Answered by
markwhitfeld
May 31, 2021
Replies: 1 comment 1 reply
-
Hi @bhagavan44 The issue here is that your call the the
const sorted = [...state.data].sort((a, b) => (a.name > b.name) ? -1 : 1);
@Selector([AccountState.getData])
static getSortedData(data: AccountStateModel['data']) {
if (data) {
return [...data].sort((a, b) => (a.name > b.name) ? -1 : 1);
}
return data;
} PS. I would also recommend making provision for equality in your sort lambda: (a, b) => (a.name > b.name) ? -1 : ( a.name === b.name ? 0 : 1 ) |
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
splincode
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi @bhagavan44 The issue here is that your call the the
sort
method would cause a mutation of the state (javascript sort mutates the underlying array). I would recommend 2 things:data
property, as opposed to the whole account state.This would ensure that the selector would only recalculate when the
data
property changes, and not when any property of theAccountState
changes.Note: for the following code, ensure that the selector option
injectContainerState
is set tofalse
(see recommendation here) or move this selector out of theA…