Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

455
Views
Why is this Array.prototype.reduce method not working
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.

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

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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));

about 4 years ago · Juan Pablo Isaza Report

0

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);

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!