Search code examples
javascriptecmascript-6

Reducing an array with multiple condition need the clarity


I got this code with one of my office challange.

const arr = [5,10,15,'C','D', '+'];
  1. 'C' remove the previous value from the array - now arr = [5,10,'D', '+'];
  2. 'D double the value in previous - now arr = [10,20,'+'];
  3. '+' sums the value - now arr = [30]

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);

LIVE DEMO


Solution

  • 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);