Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

97
Views
Obtenga un elemento de matriz y agréguelo a otros elementos en Javascript

Tengo dos matrices con la misma longitud. Quiero obtener un elemento de una matriz y continuar agregando su valor (+1) a los demás elementos hasta que el valor sea 0.

Aquí está mi código:

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

Entonces lo que hace es eso;

  1. toma el índice 3 de Array a que es 8 --> a[3] se convirtió en 0

  2. continúe agregando (+1) a sí mismo y a otros elementos de ambas matrices hasta que termine a[3].

Pero aquí está el desafío, quiero pasar por el último elemento de otra matriz (podría ser una matriz a o b ) y nunca agregar +1. Así que mi respuesta debería ser:

 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 answers
Answer question

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

El cambio más importante es la condición (index === source[target].length || target !== target_param && index === source[target].length - 1) y no mutar los parámetros de la función.

Recomiendo encarecidamente nunca mutar los parámetros de la función.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!