Array reduction
codewars kyu6
by trentHarlem
HTML
incomplete
JavaScript
function solve(n) {
const arr = []
const res = []
for (let i = 1; i <= n; i++) {
arr.push(i)
}
//console.log('arr', arr)
let copy = arr.slice()
for (let j = 0; j < arr.length; j++) {
console.log(j)
console.log(copy[j])
if (copy[j] === 1) {
res.push(copy.shift());
console.log('res', res)
}
else if (copy[j] > 1) {
let s = copy.shift()
res.push(s);
//console.log('s', s)
console.log('res', res)
copy = copy.filter(n => n % s === 0)
//console.log('copy', copy)
}
}
console.log('res', res)
//console.log('arr', arr)
console.log('copy', copy)
return res.reduce((a, c) => a + c, 0)
}
console.log(solve(7), 18)
//console.log(solve(25), 107);
/* const myArr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
const myNewArr = []
const filt = n => n % 2 !== 0
console.log('myArr',myArr)
console.log(myNewArr.push(myArr.shift()))
console.log('myArr',myArr)
console.log(myArr.filter(n => n % 2 === 0).map(n=>n))
console.log('newArr',myNewArr)
//console.log('filt', myArr.filter(filt))
console.log('myArr',myArr)
*/
//////////////////Prototypes
/*
// Reduce Only
if (Array.prototype.mapIf === undefined) {
Array.prototype.mapIf = function(predicateFn, applyFn) {
return this.reduce((ref, el) => predicateFn(el) ? ref.concat(applyFn(el)) : ref, []);
};
}
// Filter + Map
if (Array.prototype.mapIf === undefined) {
Array.prototype.mapIf = function(predicateFn, applyFn) {
return this.filter(predicateFn).map(applyFn);
};
}
console.log(myArr.mapIf(filt, f =>f))
*/
///////////////////////