3gwebtrain
3gwebtrain

Reputation: 15299

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

Upvotes: 1

Views: 248

Answers (3)

Hao Wu
Hao Wu

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

Serhii Kuts
Serhii Kuts

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

Layhout
Layhout

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

Related Questions