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

175
Visualizações
Only the last element is added to the array?

When I am adding elements to an array, only the last element is added to the array? I cant find out what is wrong in the closure.

const data = require('../content/data')

function randomize() {
    const ds_size = Math.floor(Math.random() * 500) + 50 //Generate no of objects in stream
    let name_index = 0
    let origin_city_index = 0
    let destination_city_index = 0
    let org_message = {
      name: '',
      origin: '',
      destination: ''
    }
    let ds = [];
    return function getDs() {
      for(let i = 0; i< ds_size; i++) {
        name_index = Math.floor(Math.random() * data.names.length)
        origin_city_index = Math.floor(Math.random() * data.cities.length)
        destination_city_index = Math.floor(Math.random() * data.cities.length)
        org_message.name = data.names[name_index]
        org_message.origin = data.cities[origin_city_index]
        org_message.destination = data.destination[destination_city_index]
        ds.push(org_message)
      }
      return ds
    }
}

module.exports = {randomize}
about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

You are reusing the same org_message object for every entry in the array so all the array elements will point at exactly the same object (however you last modified the object) and thus will all contain the exact same thing.

Instead, create a new object for each iteration of the loop so each element of the array contains its own object. In Javascript objects are passed to functions, returned from functions or inserted into arrays as pointers, not copies. So, ds.push(org_message) just pushes a pointer to org_message into the array, thus you must create a new object for each element of the array if you want them to all be different.


const data = require('../content/data')

function randomize() {
    const ds_size = Math.floor(Math.random() * 500) + 50 //Generate no of objects in stream
    let name_index = 0
    let origin_city_index = 0
    let destination_city_index = 0
    return function getDs() {
      let ds = [];
      for(let i = 0; i< ds_size; i++) {
        let org_message = {
          name: '',
          origin: '',
          destination: ''
        };
        name_index = Math.floor(Math.random() * data.names.length)
        origin_city_index = Math.floor(Math.random() * data.cities.length)
        destination_city_index = Math.floor(Math.random() * data.cities.length)
        org_message.name = data.names[name_index]
        org_message.origin = data.cities[origin_city_index]
        org_message.destination = data.destination[destination_city_index]
        ds.push(org_message)
      }
      return ds
    }
}

module.exports = {randomize}

I also moved the declaration of ds inside the returned function because without that, you will be reusing the same ds array each time the returned function is called which will just be adding more elements to the end of the same array and it will be modifying the array that was returned on previous calls.

Please remember that objects in Javascript are used by pointer so passing one or returning one passes a pointer to the object - the object is not copied.

about 4 years ago · Santiago Trujillo 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