Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading