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

187
Visualizações
Reducing an array of strings into individual strings using JS

I am trying to reduce an array of strings into individual strings, it works well only if i have one string within each array, but not more than one.

const listItems = [
  {
    sys: {
      type: 'Link',
      linkType: 'Entry',
      id: 'm-list-basic-1'
    }
  },
  {
    sys: {
      type: 'Link',
      linkType: 'Entry',
      id: 'm-list-basic-2'
    }
  },
  {
    sys: {
      type: 'Link',
      linkType: 'Entry',
      id: 'm-list-basic-3'
    }
  }
];

const listIds = listItems.reduce((a, currentValue) =>
            [...a, currentValue.sys.id], [])

// I have also tried `mlistId.toString()`
console.log(...listIds)

Currently i get, for example:

m-list-basic-1 m-list-basic-2 m-list-basic-3 (all on the same line using spread)

m-list-basic-1,m-list-basic-2,m-list-basic-3 (comma'ed using toString()

whereas i want them individual like so:

m-list-basic-1

m-list-basic-2

m-list-basic-3

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

If you're trying to print the id as a new line separated string, you don't need reduce to do this. Instead, you want to use Array.map, combined with String.join with a \n character.

See example below:

const listItems = [
  {
    sys: {
      type: 'Link',
      linkType: 'Entry',
      id: 'm-list-basic-1'
    }
  },
  {
    sys: {
      type: 'Link',
      linkType: 'Entry',
      id: 'm-list-basic-2'
    }
  },
  {
    sys: {
      type: 'Link',
      linkType: 'Entry',
      id: 'm-list-basic-3'
    }
  }
];

console.log(listItems.map(item => item.sys.id).join('\n'));

about 4 years ago · Juan Pablo Isaza Relatório

0

Try with forEach:

const listItems = [
  {
    sys: {
      type: 'Link',
      linkType: 'Entry',
      id: 'm-list-basic-1'
    }
  },
  {
    sys: {
      type: 'Link',
      linkType: 'Entry',
      id: 'm-list-basic-2'
    }
  },
  {
    sys: {
      type: 'Link',
      linkType: 'Entry',
      id: 'm-list-basic-3'
    }
  }
];

const listIds = listItems.reduce((a, currentValue) =>
            [...a, currentValue.sys.id], [])

listIds.forEach(l => console.log(l))

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