-1

// 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.

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]

  • Your second reduce callback is returning acc1.push(val) instead of returning acc1. – James Mar 24 '23 at 02:32
  • so i have to give return without push command like below, ''' return arr.reduce((acc1, val1) => (count(acc1, val1) < n) ? (acc1.push(val1) ? acc1: acc1): acc1, []); ''' this is working. but is this effective way of writing code? – Chidambaram P Mar 24 '23 at 02:37
  • If you delete the else clause from the commented code it should work fine as a replacement. I would avoid forcing ternaries, if they don't work nicely don't use them, it makes the code really hard to understand. – James Mar 24 '23 at 02:40
  • commented code is working fine (multi lines in reduce code. single line reduce statement is not working becoz of push command in return – Chidambaram P Mar 24 '23 at 02:47
  • Change `acc1.push(val1)` to `acc1.push(val1) && acc1`, that's all to chain operations and return acc1 – tom10271 Mar 24 '23 at 02:58

1 Answers1

0

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]
Unmitigated
  • 76,500
  • 11
  • 62
  • 80