Matthew Harwood Matthew Harwood - 1 month ago 4
Javascript Question

How to rewrite an Array.every() in a custom Array.reduce() in javascript?

This question is for purely for learning purposes. funfunfunction on youtube says that


Any list higher order list transformation can be written in
Array.reduce()



Audio/video Reference: https://youtu.be/Wl98eZpkp-c?t=138.

Question:

Purely for learning how would one rewrite
Array.every()
with
Array.reduce()


This question stems from my previous question here

Javascript Example:

var approved1 = [

{
dateApproved: new Date(),
id: 1,
},
{
dateApproved: new Date(),
id: 2,
}
];

var approved2 = [

{
dateApproved: null,
id: 1,
},
{
dateApproved: new Date(),
id: 2,
}
];

approved1.every(a => a.dateApproved != null) ? 'APPROVED' : 'PENDING'
// 'APPROVED'
approved2.reduce(every) ? 'APPROVED' : 'PENDING'
// 'PENDING'


I struggle with where I store the currently passed values. Where do I store the "passed" values like
Array.every()
does?

function every(previousValue, currentValue, currentIdx, arr) {
if(previousValue.dateApproved !== null && currentValue.dateApproved !== null) {
return currentValue;
}
}

Answer
 var status = approved1.reduce(  val  =>  (val.dateApproved) ? 'APPROVED': 'REJECTED')

var approved1 = [

    {
        dateApproved: new Date(),
        id: 1,
    },
    {
        dateApproved: new Date(),
        id: 2,
    }
];

var approved2 = [

    {
        dateApproved: null,
        id: 1,
    },
    {
        dateApproved: new Date(),
        id: 2,
    }
];

console.log(approved1.reduce(  val  =>  (val.dateApproved) ? 'APPROVED': 'REJECTED'))


console.log(approved2.reduce(  val  =>  (val.dateApproved) ? 'APPROVED': 'REJECTED'))

Comments