Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript – single line reduce statement not working becoz of push statement

// only have numbers in array till n times

function deleteNth(arr,n){
    // ...
    function count(arr1, num){
        console.log('arr1', arr1)
        return arr1.reduce((acc, val) => (val === num) ? ++acc : acc, 0);
    }
    // return arr.reduce((acc1, val1) => {
    //     if (count(acc1, val1) < n){
    //         acc1.push(val1);
    //     }
    //     else{
    //         acc1;
    //     }
    //     return acc1;
    // }, []);
    return arr.reduce((acc1, val1) => ((count(acc1, val1) < n) ? acc1.push(val1) : acc1), []);
  }

  
console.log(deleteNth([20,37,20,21], 1));    // [20,37,21]`

when i run with this code am getting error.
TypeError: arr1.reduce is not a function

however when i run with the commented code, its running fine.
with multiple lines of code in reduce function, its working fine.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

in single line code, variable acc1 is having value 1 when first array element is processed. due to this am getting error.
can anyone advise what mistake am doing?

console.log(deleteNth([20,37,20,21], 1)); // [20,37,21]

>Solution :

It doesn’t work because you should be returning the array in the reduce callback, but one branch of the ternary is returning the result of push, which is the new length of the array.

You could exploit the logical and operator to push only when the condition is true and use the comma operator to always return the accumulator array at the end.

function deleteNth(arr, n) {
  function count(arr1, num) {
    return arr1.reduce((acc, val) => (val === num) ? ++acc : acc, 0);
  }
  return arr.reduce((acc1, val1) => (count(acc1, val1) < n && acc1.push(val1), acc1), []);
}
console.log(deleteNth([20, 37, 20, 21], 1)); // [20,37,21]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading