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

143
Visualizações
Get a value from one array and add to remaining elements of both Array in JS

Let's say I have the following 2 Arrays:

let a = [5,5,5,5,0]
let b = [5,5,5,5,0]

Assuming that both arrays has the same length:

I want to get a value from an element of one Array and add the +1 itself and to other remaining elements. If the the picked value is still bigger than zero, then it should also continue adding it to elements of other array from starting index.

Example_1: If I pick a[2] then the outcome should be:

a = [5,5,1,6,1] // a[2] became 0 after picking 5, then in each remaining element we add +1 and continue to next array.
b = [6,6,5,5,0]

Example_2: Or If I pick b[3] from initial arrays, then the outcome should be:

a = [6,6,6,5,0] // b[3] became 0 after picking 5, then in each remaining element we add +1 and move to next array until our value becomes zero
b = [5,5,5,1,1]

Here is my attempt:

let pickedValue = a[2]

for (let index = 2; index < a.length; index++) {
    if (pickedValue > 0) {
        a[index] += 1
        pickedValue--
    }
}
for (let index = 0; index < pickedValue; index++) {
    if (pickedValue > 0) {
        b[index] += 1
        pickedValue--
    }
}

Can we do this in more dynamic way with maybe one loop?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You could tkae an object with same named properties of arrays and hand over target key and index and then update until no more value is to disperse.

const
    update = (source, target, index) => {
        const keys = Object.keys(source);
        let value = source[target][index];
        source[target][index] = 0;
        while (value--) {
            source[target][index++]++;
            if (index === source[target].length) {
                index = 0;
                target = keys[(keys.indexOf(target) + 1) % keys.length];
            }
        }
        return source;
    };

console.log(update({ a: [5, 5, 5, 5, 0], b: [5, 5, 5, 5, 0] }, 'a', 2));
console.log(update({ a: [5, 5, 5, 5, 0], b: [5, 5, 5, 5, 0] }, 'b', 3));
.as-console-wrapper { max-height: 100% !important; top: 0; }

about 4 years ago · Juan Pablo Isaza Relatório

0

You just need to iterate through both arrays. The chosen array should be iterated from the target + 1 up to its lenght, and the other array, from 0 up the target. You can see that I directly put a 1 to the chosen array at index target, instead of put a 0 and add +1.

(Also use some regex in order to catch the number between the brackets, from this SO answer)

let a = [5,5,5,5,0]
let b = [5,5,5,5,0]


const ans = prompt("Pick an element (e.g `a[2]` or `b[3]`)");

const [chosenArray, otherArray] =  ans[0] === 'a' ? [a, b] : [b, a];
const target = parseInt(ans.match(/(?<=\[).+?(?=\])/), 10);

chosenArray[target] = 1;
for (let i = target + 1; i < chosenArray.length; ++i)
  ++chosenArray[i];
for (let i = 0; i < target; ++i) 
  ++otherArray[i];


console.log(a, b)

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