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?

>Solution :

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)

Leave a Reply