Using functional methods such as map,filter,reduce, how can a nested for loop that is imperative be converted to a declarative function. Using the below as an example:
getTxns: function () {
var txnsToCheck = [];
var pages = this.data;
for (var i = 0; i < pages.length; i++) {
var page = pages[i];
var txns = [];
for (var j = 0; j < page.txns.length; j++) {
if (page.txns[j].grade) {
txnsToCheck.push({ page: i, txn: j, virtual: false });
}
else {
txnsToCheck.push({ page: i, txn: 0, virtual: true });
}
}
return txnsToCheck;
},
Below is non working attempt at a functional rewrite, the last map does not work, but I believe illustrates the intent, which is a conditional assignment.
getTxns: function () {
return this.data.
map(function (page) {
return page.txns.
map(function(txn){
if (txn.grade){
return {page: txn.page_idx, txn: page.txns.indexOf(txn), virtual: false}
} else {
return {page: txn.page_idx, txn: 0, virtual: true}
}
})
})
I have considered filter, but its not clear if you can traverse back up the chain for a second filter and map in one operation?
Wondering what a working declarative version of the for loop looks like.
Here is an example of what the data schema looks like:
"derived": [
{
"page_idx": 0,
"page_image_url": "",
"doc_pk": 123456,
"txns": [
{
"page_idx": 0,
"grade": 0,
"explanation": "test 1",
"id": 1962754,
},
{
"page_idx": 0,
"is_recurring": false,
"bank_account_pk": null,
"grade": 0,
"explanation": "test 2",
"id": 1962753,
},
]
},
{
"page_idx": 1,
"page_image_url": "",
"doc_pk": 2654321,
"txns": []
},
{
"page_idx": 2,
"page_image_url": "",
"doc_pk": 123457,
"txns": []
}
]
reduce.