Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

159
Visualizações
Parse out the nested elements of an array into the main array

What is the most efficient way to move the elements within the nested portion of the inner array out into the main array?

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

my attempt

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

actual outcome

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

desired outcome

[ 'one', 'two', 'three', 'four' ]
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

There is a built-in prototype function in Array called flat for that purpose.

One parameter: The depth level specifying how deep a nested array structure should be flattened. Defaults to 1.

flat() will flat a 2D to 1D flat(2) will flat out a 3D to 1D.

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

about 4 years ago · Juan Pablo Isaza Relatório

0

flat function is what you are looking for.

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

about 4 years ago · Juan Pablo Isaza Relatório

0

Either use the Array#flat() method, like Amila Senadheera suggested, or change your function to not always add the element to the new array, like so:

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda