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

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

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 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