Reputation: 15299
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);
Upvotes: 1
Views: 248
Reputation: 20859
Here's a solution using mappings:
const arr = [5, 10, 15, 'C', 'D', '+'];
const functions = {
'C': arr => arr.slice(0, arr.length - 1),
'D': arr => arr.map(e => e * 2),
'+': arr => [arr.reduce((acc, cur) => acc + cur)]
}
const result = arr.reduce((acc, cur) => {
if (functions[cur]) {
return functions[cur](acc);
} else {
return [...acc, cur];
}
}, []);
console.log(result);
Upvotes: 3
Reputation: 449
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);
Upvotes: 4
Reputation: 1590
when v == "C"
, you splice the array taking out 15
and "C"
making "D"
takes the "C"
place. so when reduce loops and runs again, the "D"
get skipped and v == "+"
.
Upvotes: 1