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

145
Vistas
Modify repeated values in javaScript

There is an array of JavaScript:

let arr=[
[220,A,12],
[560,B,5],
[300,A,0],
[300,H,3], 
[300,K,T],
[450,P,9],
[500,E,6],
[500,M,8]
];

The first element of sub-arrays have some repeated values,
I want to find them and modify the repeated values, as follow:

[300,A,0],  ===>  remain unchanged
[300,H,3],  ===>  [320,H,3],  //First element add 20
[300,K,T],  ===>  [340,K,T],  //First element add 20 again

[500,E,6],  ===>  remain unchanged
[500,M,8]   ===>  [520,M,8] //First element add 20

That is, the first element adds 20 in proper order if repeated.
Other elements don't need to be considered.
How to do it in javaScript?

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

One option is to use reduce. I pass an object as the initial value to reduce:

{
    last: null,  // The previous number encountered
    offset: 20,  // The amount to add on repeat
    data: []     // The new array
}

Then, use this to build the new array:

let arr=[
[220,'A',12],
[560,'B',5],
[300,'A',0],
[300,'H',3], 
[300,'K','T'],
[450,'P',9],
[500,'E',6],
[500,'M',8]
];

arr = arr.reduce((prev, cur) => {
    // Is this a repeat?
    if (prev.last == cur[0]) {
        cur[0] += prev.offset;
        prev.offset += 20;
    }
    // Not a repeat. Reset.
    else {
        prev.last = cur[0];
        prev.offset = 20;
    }
    prev.data.push(cur);
    return prev;
}, {last: null, offset: 20, data: []}).data;

console.log(arr);

about 4 years ago · Juan Pablo Isaza Denunciar

0

using map key:value, where key is number and value is its occurrence so far

let arr = [
  [220, 12],
  [560, 5],
  [300, 0],
  [300, 3],
  [300, 0],
  [450, 9],
  [500, 6],
  [500, 8]
];

m = {}

for (let i = 0; i < arr.length; ++i) {
   const x = arr[i][0]
    if (m[x] > 0){
      arr[i][0] += (m[x]) *20
      m[x]++
   } else m[x] = 1
}

console.log(arr)

about 4 years ago · Juan Pablo Isaza 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