let a1, a2, a3, a4; a1 = [1, 2, 3, 4]; a2 = a1.map(x => x*x); //[1, 4, 9, 16] a3 = a1.map(x => x*x*x); //[1, 8, 27, 64] a4 = a1.map(x => x + 1); //[2, 3, 4, 5]
let a1, a2, a3, a4; a1 = ['Riya', 'Asha', 'Anna']; a2 = a1.map(name => 'Ms. ' + name); //['Ms. Riya', 'Ms. Asha', 'Ms. Anna'] a3 = a1.map(name => name.toLowerCase()); //['riya', 'asha', 'anna'] a4 = a1.map(name => name.length) //[4, 4, 4]
let a1, a2, a3, a4; a1 = ['Riya', 'Asha', 'Anna']; a2 = a1.map((name, index) => `Ms. ${name} (${index})`); //[ 'Ms. Riya (0)', 'Ms. Asha (1)', 'Ms. Anna (2)' ]
let a1, a2, a3, a4; a1 = [40, 10, 30, 20]; a2 = a1.filter(x => x > 20) //[40, 30] a3 = a1.filter(x => x >= 15 && x <= 35) //[30, 20] a4 = a1.filter(x => x === 8) //[]
let a1, a2, a3, a4; a1 = ['Riya', 'Asha', 'Anna']; a2 = a1.filter(name => name.startsWith('A')) //['Asha', 'Anna'] a3 = a1.filter(name => !name.startsWith('A')) //['Riya']
runningSum | each |
---|---|
0 | 40 |
0+40=40 | 20 |
40+20=60 | 30 |
60+30=90 | 10 |
let array, fct, sum; array = [40, 20, 30, 10]; fct = (runningSum, each) => runningSum + each; sum = array.reduce(fct, 0); prn(sum); //100
runningSum: 0 each: 40 runningSum: 40 each: 20 runningSum: 60 each: 30 runningSum: 90 each: 10 100
let array, fct, sum; array = [40, 20, 30, 10]; fct = (runningSum, each) => { prn("runningSum: " + runningSum); prn("each: " + each); return runningSum + each; } sum = array.reduce(fct, 0); prn(sum); //100
let names, shorterFct, shortest; names = ['Asha', 'Jemima', 'Anna', 'Vy']; shorterFct = (nm1, nm2) => (nm1.length < nm2.length) ? nm1 : nm2; shortest = names.reduce(shorterFct); prn(shortest); //Vy prn(shortest.length); //2
let keyValues, fct, map; keyValues = [['firstName', 'Asha'], ['lastName', 'Kingston']]; //fct takes a map as the "accumulator" //and adds a new entry for each array element fct = (aMap, eachPair) => {aMap[eachPair[0]] = eachPair[1]; return aMap;} //reduce it (starting with empty map as accumulator) map = keyValues.reduce(fct, {}); //two ways to use map const fn = map.firstName, ln = map['lastName']; prn(`Full Name: ${fn} ${ln}`); //Full Name: Asha -- Kingston
separate by newlines bodyOnly=true
reduceConcatenate() { let a = [10, 20, 30, 40]; prn(a); prn(a.reduce((s, ea) => s + ea + '\n', '')); //output is four lines, one for each element }