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

161
Views
How to functionally increase number in array if previous one is lower

I have array of numbers that decreases, but I want it never to decrease:

const numbers =[0,1,2,3,4,5,1, 2];

Desired result is:

[0, 1, 2, 3, 4, 5, 5, 5]

I know how to achieve it with for loop:

for (let index = 0; index < numbers.length; index++) {
    const element = numbers[index];
    if (index > 0) {
      const prevEl = numbers[index - 1];
      if (element < prevEl) {
        numbers[index] = prevEl;
      }
    }
  }

But when using map

numbers.map((item, index) => {
    const prevEl = numbers[index - 1];
    if (item < prevEl) {
        return prevEl;
      }
    return item;
})

const numbers = [0,1,2,3,4,5,1, 2];

const result = numbers.map((item, index) => {
    const prevEl = numbers[index - 1];
    if (item < prevEl) {
        return prevEl;
      }
    return item;
});

console.log(result); // [0, 1, 2, 3, 4, 5, 5, 2]

I get this instead: [0, 1, 2, 3, 4, 5, 5, 2]

What would be the functional way to achieve this?

about 4 years ago · Santiago Gelvez
1 answers
Answer question

0

You could use Math.max between the current and the preceding entries in the list:

const numbers = [0,1,2,3,4,5,1, 2];

result = numbers.map((v, i, a) => Math.max(v, ...a.slice(0, i)))
console.log(result)

Note that you could/should just use Math.max(...a.slice(0, i+1)) since v is a[i], I wrote it the way I did for clarity as to what the code is doing.

about 4 years ago · Santiago Gelvez 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!