/**
* predicate(accumulator, arrayItem) : accumulator
*/
function reduce(arr, predicate, initValue) {
//initialise accumulator to the initial value
let accumulator = initValue;
// iterator over each item,
// send acuumulator and array item to predicate
for (i = 0; i < arr.length; i++) {
accumulator = predicate(accumulator, arr[i]);
}
// return the final accumulator
return accumulator;
}
/**
* predicate(arrayItem) : arrayItem
*/
function map(arr, predicate) {
// call reduce where the initial value is an empty array,
// and in the predicate push to the accumulator array,
// whatever the predicate returns
return reduce(arr, (acc, i) => {
let r = predicate(i);
acc.push(r);
return acc;
}, []);
}
/**
* predicate(arrayItem) : bool
*/
function filter(arr, predicate) {
// call reduce where the initial value is an empty array,
// and if the predicate returns true, add the item
// to the accumulator array
return reduce(arr, (acc, i) => {
if (predicate(i)) acc.push(i);
return acc;
}, []);
}
// test array
let arr = [{
name: 'Mladen',
age: 40
}, {
name: 'Dan',
age: 21
}, {
name: 'Tijana',
age: 37
}];
// tests
let totalAge = reduce(arr, (acc, item) => acc = acc + item.age, 0);
console.log('Total Age (reduce): ',totalAge);
let names = map(arr, (i) => i.name);
console.log('Only Names (map):', names);
let over21 = filter(arr, (i) => i.age > 21);
console.log('Over 21 (filter):', over21);
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.