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

209
Views
¿Cómo agregar elementos de matrices al final de la matriz?

Hay sourceArray y algunos additionalArray . Necesita additionalArray elementos de AdditionalArray al final de sourceArray . Y en el resultado sourceArray contiene todos los elementos (sin crear una nueva matriz). El problema es que el recuento de elementos de additionalArray puede ser de miles.

 // example push([], [1, 2, 3], [10, 20, 30]) // [1, 2, 3, 10, 20, 30] push(['a', 'b'], 'x', ['z', '0']) // ['a', 'b', 'x', 'z', '0']
 // my solution function push(sourceArray, ...additionalArray) { additionalArray.forEach((array) => { array = Array.isArray(array) ? array : [array]; if (array.length < 1000) { sourceArray.push.apply(sourceArray, array); } else { array.forEach((item) => sourceArray.push(item)); } }); return sourceArray; }

Mi pregunta, ¿hay una solución más elegante para esta tarea?

about 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Puede encontrar que usar .flat() puede ayudarlo aquí. Si usa eso en additionalArray , puede luego distribuir ... esos elementos en una llamada a .push() como argumentos:

 const push = (source, ...rest) => { source.push(...rest.flat()); return source; } console.log(push([], [1, 2, 3], [10, 20, 30])) // [1, 2, 3, 10, 20, 30] console.log(push(['a', 'b'], 'x', ['z', '0'])) // ['a', 'b', 'x', 'z', '0']

Sin embargo, esto tiene una limitación en el sentido de que .push() solo puede aceptar una cierta cantidad de argumentos. Es posible que alcance el límite máximo de argumentos y esto puede arrojar si considera que su additionalArray puede ser grande. Usar un bucle for..of ayudaría con eso:

 const push = (source, ...rest) => { for(const item of rest.flat()) source.push(item) return source; } console.log(push([], [1, 2, 3], [10, 20, 30])) // [1, 2, 3, 10, 20, 30] console.log(push(['a', 'b'], 'x', ['z', '0'])) // ['a', 'b', 'x', 'z', '0']

about 4 years ago · Santiago Trujillo Report

0

A partir de MDN , puede usar la sintaxis de distribución de matriz:

 let vegetables = ['parsnip', 'potato'] let moreVegs = ['celery', 'beetroot'] // Merge the second array into the first one vegetables.push(...moreVegs); console.log(vegetables) // ['parsnip', 'potato', 'celery', 'beetroot']
about 4 years ago · Santiago Trujillo 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!