Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

144
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda