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