How to use reduce in this algorithm? [closed]

    /*
     When consecutive values come into the array, 
     delete and count the number

      I want to this result
      count = 4 // [1, 1, 3, 3]
      array = [4, 2, 4]
    */
    
    let count = 0;
    let array = [4, 3, 1, 1, 3, 2, 4]
 
    array.reduce((acc, cur) => {
      if (acc[acc.length - 1] === cur) {
        acc.pop()
        count += 2
      } 
        // this part
        else return acc.concat(cur)
    }, [])

enter image description here

I don’t know why the above error occurs when I write ‘else’ word in the code and

I want the result in the comment. How is it good to solve it?

Answer

You need to assign the result of your reduce operation and also return the accumulator inside your if block too for next iterations:

/*
  I want to this result
  count = 4 // [1, 1, 3, 3]
  array = [4, 2, 4]
*/

let count = 0;
let array = [4, 3, 1, 1, 3, 2, 4]
 
array = array.reduce((acc, cur) => {
  if (acc[acc.length - 1] === cur) {
    acc.pop()
    count += 2;
    return acc;
  } else {
    return acc.concat(cur);
  } 
}, []);

console.log({count, array});

Leave a Reply

Your email address will not be published. Required fields are marked *