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

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

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 Denunciar

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