0

I'm trying to learn es6 and playing around with the pokemon API. myRoute = 'https://pokeapi.co/api/v2/ability/144/';

const arrObservable = this._http.get(newurl);
 arrObservable.subscribe( 
(data) => {
 const pokeString = data.pokemon.map( ( { pokemon }: obj ) => pokemon.name );
console.log(`There are ${data.pokemon.length} pokemon with the ${data.name} ability:  ${pokeString}`);

})

output:

There are 19 pokemon with the regenerator ability: slowpoke,slowbro,tangela,slowking,corsola,ho-oh,tangrowth,audino,solosis,duosion,reuniclus,foongus,amoonguss,alomomola,mienfoo,mienshao,mareanie,toxapex,tornadus-therian

I am getting the correct results, it just looks a bit icky in the console, so I'm wondering if there is a way to add a '\n' every few lines while still using the .map() function?

Val14720
  • 45
  • 10
  • 1
    https://stackoverflow.com/questions/8495687/split-array-into-chunks and https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join – Blue Oct 11 '18 at 06:24
  • What you actually need is `.join(", ")` - notice the space! – Bergi Oct 11 '18 at 06:56

1 Answers1

2

Once you've used .map, join by commas, and then use .replace on the resulting string to replace instances of 3 words separated by commas with those 3 words and commas plus a newline. That way, your pokeString will actually be a string:

const pokeString = data.pokemon
  .map( ( { pokemon }: obj ) => pokemon.name )
  .join(',')
  .replace(/[^,]+,[^,]+,[^,]+,/g, '$&\n');

const names = ['slowpoke','slowbro','tangela','slowking','corsola','ho-oh','tangrowth','audino','solosis','duosion','reuniclus','foongus','amoonguss','alomomola','mienfoo','mienshao','mareanie','toxapex','tornadus-therian'];

const pokeString = names
  .join(',')
  .replace(/[^,]+,[^,]+,[^,]+,/g, '$&\n');
  
console.log(pokeString);
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320