How Can I Group Specific Items Within An Object In The Same Array And Delete Them From The Core Array?
Solution 1:
Here is one technique:
// helper functionconstaddChecked = (q, qs) =>
({...q, questionGroup: qs .filter (p => p .checked)})
// main functionconstnestChecked = (qs, found = false) =>
qs .flatMap (q => q .checked ? found ? [] : (found = true, [addChecked (q, qs)]) : [q])
// sample dataconst dummyQuestions = [{id: 1, checked: false, question: 'foo', questionGroup: []}, {id: 2, checked: true, question: 'bar', questionGroup: []}, {id: 3, checked: false, question: 'baz', questionGroup: []}, {id: 4, checked: true, question: 'qux', questionGroup: []}, {id: 5, checked: true, question: 'corge', questionGroup: []}]
// democonsole .log (JSON .stringify (nestChecked (dummyQuestions), null, 4))
.as-console-wrapper {max-height: 100%!important; top: 0}
We have a simple helper function that groups all the checked elements of the input into (a copy of) a specific question.
Our main function iterates over the questions with .flatMap
, which allows us to do a filter and map in a single traversal. We maintain a flag, found
which tells us if we've already handled the checked elements. For each question, if it's not checked, we simply include it, by returning it wrapped in an array, as [q]
from the flatMap
callback. If it is checked, we evaluate the found
flag. If that is set to true
, then we return and empty array. If it's not, we return the result of calling our helper function above, again wrapped in an array. (These array wrappers are not specifically needed for this problem; but I like to return a consistent type in the flatMap
callback.)
We could easily inline that helper function, as it's only called once. In fact that's how I originally wrote it. But it feels cleaner to me separated.
It's not clear to me if there is some iterative process which will then further nest these. If so, you might have to do something more sophisticated in the helper function dealing wit already-populated questionGroup
fields. But that would probably be for a different question.
Finally, we also might want to avoid that default parameter. There are sometimes good reasons to want to do so. I leave this change as an exercise for the reader. :-)
Post a Comment for "How Can I Group Specific Items Within An Object In The Same Array And Delete Them From The Core Array?"