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

101
Visualizações
Get an element of array and add to other elements in Javascript

I have two arrays with same length. I want to get an element from one array and continue adding its value (+1) to each other elements until value is 0.

Here is my code:

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: [0, 0, 0, 8, 0], b: [0, 0, 0, 0, 0]}, 'a', 3))

answer: { a: [ 1, 0, 0, 1, 1 ], b: [ 1, 1, 1, 1, 1 ] }

So what it does is that;

  1. it takes index 3 of Array a which is 8 --> a[3] became 0

  2. continue adding (+1) to itself and other elements of both arrays until a[3] is over.

But here is the challenge, I want to pass by the last element of other array(could be array a or b) and never add +1. So my answer should be:

answer: { a: [ 1, 1, 0, 1, 1 ], b: [ 1, 1, 1, 1, 0 ] } --> last element of b not changed!

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

0

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

console.log(update({a: [0, 0, 0, 8, 0], b: [0, 0, 0, 0, 0]}, 'a', 3))

The most important change being the condition (index === source[target].length || target !== target_param && index === source[target].length - 1) and not mutating the function params.

I strongly suggest never mutating the function parameters.

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