I got this code with one of my office challange.
const arr = [5,10,15,'C','D', '+'];
I am trying to achieve this goal using array
reduce
method. but for me D
is not console the value at all.
What is the correct way? Here is my try:
const arr = [5,10,15,'C','D', '+'];
const result = arr.reduce((c,v,i,a) => {
if(v=='C'){
a.splice(i-1, i-1);
}
if(v=='D'){
console.log(i) //console not works
}
return c + (Number(v) ? v:0);
}, 0);
console.log(result);
const arr = [5, 10, 15, 'C', 'D', '+'];
const result = arr.reduce((acc, curr) => {
if (curr === 'C') {
acc.pop(); // remove the previous value from the array
} else if (curr === 'D') {
acc= acc.map(x=>x*2); // double the value of the ALL elements
} else if (curr === '+') {
const sum = acc.reduce((sum, val) => sum + val, 0); // sum all
return [sum]; // return the sum as a single element array
} else {
acc.push(curr); // add the current element to the accumulator
}
return acc;
}, []);
console.log(result);