I need help with this code ES6

0

I'm trying to get the data that's coming this way:

[
    {
        "name":"JONAS",
        "languages":["php","javascript","java"],
        "age":37,
        "graduate_date":1044064800000,
        "phone":"32-987-543"
    },
    {
        "name":"FLAVIO",
        "languages":["java","javascript"],
        "age":26,
        "graduate_date":1391220000000,
        "phone":"32-988-998"
    },
    {
        "name":"HENRIQUE",
        "languages":["regex","javascript","perl","go","java"],
        "age":21,
        "graduate_date":1296525600000,
        "phone":"32-888-777"
    }
] 

And turn this into:

Jonas - 26 years - 32-988-998
Flavio - 21 years - 32-888-777
Henrique - 37 years - 32-987-543
go (1)
java (3)
javascript (3)
perl (1)
php (1)
regex (1)

I'm using this code:

'use strict';

const fs = require('fs');

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

const todaydate = 1517577684000;

process.stdin.on('data', inputStdin => {
inputString += inputStdin;
});

process.stdin.on('end',  => {
inputString = inputString
        .replace(/\s$/, '')
        .split('\n')
        .map(str => str.replace(/\s$/, '')),
main();
});

function readLine() {
return inputString[currentLine++];
}
// Complete the selectCandidates function below.
const reportCandidates = (candidatesArray) => {

//aqui ta o problema

return reportObject;
}

function main() {
const ws = fs.createWriteStream(process.env.OUTPUT_PATH);
const candidates = JSON.parse(readLine());
let result = reportCandidates(candidates);

// Don't touch this code or you will die
for (let i=0; i<result.candidates.length; i++){
    ws.write(result.candidates[i].name + " - " + result.candidates[i].age +" years - " + result.candidates[i].phone +"\n");
}
for (let i=0; i<result.languages.length; i++){
    ws.write(result.languages[i].lang + " - " + result.languages[i].count +"\n");
}

ws.end();
}

But I can not solve it or pray, can anyone give a light?

    
asked by anonymous 19.11.2018 / 03:07

2 answers

2

I did it this way, take a look if it helps you

const meusDados = [
  {
      "name":"JONAS",
      "languages":["php","javascript","java"],
      "age":37,
      "graduate_date":1044064800000,
      "phone":"32-987-543"
  },
  {
      "name":"FLAVIO",
      "languages":["java","javascript"],
      "age":26,
      "graduate_date":1391220000000,
      "phone":"32-988-998"
  },
  {
      "name":"HENRIQUE",
      "languages":["regex","javascript","perl","go","java"],
      "age":21,
      "graduate_date":1296525600000,
      "phone":"32-888-777"
  }
] 

const exibe = (dados) => {
  let linguagens = []
  let nomeLinguagem = []
  dados.forEach(elemento => {
    console.log('${elemento.name} - ${elemento.age} years - ${elemento.phone}')
    elemento.languages.forEach(lang => {
      if (!linguagens[lang]) {
        linguagens[lang] = 0
        nomeLinguagem.push(lang)
      }
      linguagens[lang]++
    })
  })

  nomeLinguagem.forEach(lang => {
    console.log('${lang} (${linguagens[lang]})')
  })
}

exibe(meusDados)

I used the data you gave me and created a function that makes the functionality of displaying the data as indicated.

    
19.11.2018 / 12:10
0

Not considering that you did not inform the way of entering and leaving the data, I took into account that you need 3 actions:

  • Create a line with each person's data;
  • Turn the first letter of each name in upper case;
  • Count the number of occurrences of each language and create a line with each;

For the first problem, we only need to map the original array , create a array with the target format of the line and use the #

const pessoas = dados.map(({ name, age, phone }) => '${name} - ${age} years - ${phone}');
console.log(pessoas.join('\n'));
JONAS - 37 years - 32-987-543
FLAVIO - 26 years - 32-988-998
HENRIQUE - 21 years - 32-888-777

To turn the first letter of each word in uppercase you can use the following:

nome.split(' ')
  .map(s => s.slice(0, 1).toUpperCase() + s.slice(1).toLowerCase())
  .join(' ');

And finally, to count the occurrences of each language, you can transform all join into one and transform into a array of lines with the desired format:

const contar = (dados) => {
  const ocorrencias = {};

  // Conta as ocorrências colocando-as em um objeto
  for (const linguagem of dados) {
    ocorrencias[linguagem] = (ocorrencias[linguagem] || 0) + 1;
  }

  // Transforma o objeto com a contagem em um 'array' com o formato determinado
  return [[], ...Object.keys(ocorrencias)].reduce((acumulador, item) => [...acumulador, '${item}(${ocorrencias[item]})']);
}

Putting it all together we will have:

// Transforma a primeira letra de cada palavra em maiúscula
const capitalizar = nome => nome.split(' ').map(s => s.slice(0, 1).toUpperCase() + s.slice(1).toLowerCase()).join(' ');

const contar = (dados) => {
  const ocorrencias = {};

  // Conta as ocorrências colocando-as em um objeto
  for (const linguagem of dados) {
    ocorrencias[linguagem] = (ocorrencias[linguagem] || 0) + 1;
  }

  // Transforma o objeto com a contagem em um 'array' com o formato determinado
  return [[], ...Object.keys(ocorrencias)].reduce((acumulador, item) => [...acumulador, '${item}(${ocorrencias[item]})']);
};

const transformar = (dados) => {
  const pessoas = dados.map(({ name, age, phone }) => '${capitalizar(name)} - ${age} years - ${phone}');
  // Transforma em um 'array' de linguagens
  const linguagens = contar([[], ...dados].reduce((acumulador, { languages }) => [...acumulador, ...languages]));
  const textoPessoas = pessoas.join('\n');
  const textoLinguagens = linguagens.join('\n');

  return '${textoPessoas}\n${textoLinguagens}';
};

console.log(transformar([
  {
    "name":"JONAS",
    "languages":["php","javascript","java"],
    "age":37,
    "graduate_date":1044064800000,
    "phone":"32-987-543"
  },
  {
    "name":"FLAVIO",
    "languages":["java","javascript"],
    "age":26,
    "graduate_date":1391220000000,
    "phone":"32-988-998"
  },
  {
    "name":"HENRIQUE",
    "languages":["regex","javascript","perl","go","java"],
    "age":21,
    "graduate_date":1296525600000,
    "phone":"32-888-777"
  }
]));
    
19.11.2018 / 12:47