Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

162
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda