Home > Back-end >  Why is this Array.prototype.reduce method not working
Why is this Array.prototype.reduce method not working

Time:04-17

function dropElements(arr, func) {
let output = arr.reduce((acc=[], elem) => {
    if (func(elem)){
        acc.push(arr.slice(arr.indexOf(elem)))
        return acc
    }
}, [])
return output

}

let tester = dropElements([1, 2, 3, 4,5,6,3,2,1], function(n) {return n >= 3;})

console.log(tester)

I want it to output [3,4,5,6,3,2,1]. But is printing copies of size decreasing arrays.

Can sombedoy help me with this problem?

Edit: The statement of the problem "Given the array arr, iterate through and remove each element starting from the first element (the 0 index) until the function func returns true when the iterated element is passed through it."

CodePudding user response:

You can use Array#slice along with Array#findIndex to find the first index at which the callback function returns true.

function dropElements(arr, func) {
  const idx = arr.findIndex(func);
  return idx >= 0 ? arr.slice(idx) : [];
}
console.log(dropElements([1, 2, 3, 4, 5, 6, 3, 2, 1], n => n >= 3));

If you specifically want to use Array#reduce, you could use a variable to store whether or not the callback has returned true for any element so far.

function dropElements(arr, func) {
  let found = false;
  return arr.reduce((acc, elem) => {
    found = found || func(elem);
    if (found) acc.push(elem);
    return acc;
  }, []);
}
console.log(dropElements([1, 2, 3, 4, 5, 6, 3, 2, 1], n => n >= 3));

CodePudding user response:

Use the shift method to remove the first element from the array until the array is empty or func(arr[0]) returns a truthy value. This method is inefficient as it could be, but it matches the problem statement. Particularly:

  • It removes each element singularly, rather than all at once.
  • It removes elements while iterating.
  • It operates on the array itself, rather than a copy.

function dropElements(arr, func) {
  while (arr.length > 0 && !func(arr[0])) {
    arr.shift();
  }
  return arr;
}

let tester = dropElements([1, 2, 3, 4,5,6,3,2,1], function(n) {return n >= 3;});
console.log(tester);

  • Related