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

158
Views
Analice los elementos anidados de una matriz en la matriz principal

¿Cuál es la forma más eficiente de mover los elementos dentro de la parte anidada de la matriz interna hacia la matriz principal?

Ejemplo: [1,[2,3],4] -> [1,2,3,4]

mi intento

 var old_arr = ["one", ["two", "three"], "four"]; var new_arr = []; function arrayfix(arr) { for (var i = 0; i < arr.length; i++) { if (typeof arr[i] == typeof {}) { //checks to see if it's an object for (var j = 0; j < Object.keys(arr[i]).length; j++) { new_arr.push(arr[i][j]); } } new_arr.push(arr[i]); } return new_arr; } console.log(arrayfix(old_arr));

resultado real

 [ 'one', 'two', 'three', [ 'two', 'three' ], 'four' ]

resultado deseado

 [ 'one', 'two', 'three', 'four' ]
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

Hay una función de prototipo incorporada en Array llamada plana para ese propósito.

Un parámetro: el nivel de profundidad que especifica la profundidad a la que se debe aplanar una estructura de matriz anidada. El valor predeterminado es 1.

flat() aplanará un 2D a 1D flat(2) aplanará un 3D a 1D.

 var old_arr= ["one",["two","three"],"four"]; console.log(old_arr.flat());

about 4 years ago · Juan Pablo Isaza Report

0

función plana es lo que buscas.

 var old_arr= ["one",["two","three"],"four"]; var new_arr = old_arr.flat(); console.log(new_arr);

about 4 years ago · Juan Pablo Isaza Report

0

Utilice el método Array#flat(), como sugirió Amila Senadheera , o cambie su función para no agregar siempre el elemento a la nueva matriz, así:

 var old_arr= ["one",["two","three"],"four"]; function arrayfix(arr){ let new_arr = []; for(let i =0; i < arr.length; i++) { if(typeof arr[i] == typeof {}) { //checks to see if it's an object for(let j =0; j < Object.keys(arr[i]).length; j++) { new_arr.push(arr[i][j]); } } else { // if it's an array, don't add it back to the new array new_arr.push(arr[i]); } } return new_arr; } console.log(arrayfix(old_arr));

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!