Home > Software engineering >  Reduce callback function to retrieve properties from an array
Reduce callback function to retrieve properties from an array

Time:11-22

Given the following array I am to write a callback function for reduce to return an object that has two keys-'JavaScript' & 'python'. The keys should be equal to the number of developers that have 'JavaScript' or 'python' as their language. The final console log should read JavaScript: 4, Python:3.

const developersArray = [
    { name: 'ralph', language: 'javascript' },
    { name: 'gretchen', language: 'javascript' },
    { name: 'alice', language: 'python' },
    { name: 'mohammed', language: 'javascript' },
    { name: 'pat', language: 'python' },
    { name: 'taylor', language: 'python' },
    { name: 'hideo', language: 'javascript' },
];

So far this is what i came up with. I am looking back at an old assignment and think i was on the right track but not sure if i am headed the right way:

const devLanguageCounts = developersArray.reduce(() => developersArray.language === 'javascript' && 'python' ?   developersArray : 'javascript', 'python');

Any help is greatly appreciated

CodePudding user response:

Using reduce dynamically using Logical_nullish_assignment which initial object if the language does not exist with 0 or get its previous value, then increment it.

const developers = [
  { name: "ralph", language: "javascript" },
  { name: "gretchen", language: "javascript" },
  { name: "alice", language: "python" },
  { name: "mohammed", language: "javascript" },
  { name: "pat", language: "python" },
  { name: "taylor", language: "python" },
  { name: "hideo", language: "javascript" },
];
const devLanguageCounts = developers.reduce((prev, { language }) => {
  prev[language] ??= 0;
  prev[language]  ;
  return prev;
}, {});
console.log(devLanguageCounts);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Using Simple approach with forEach with checking with hasOwnProperty if language already exist in res increment it elsewhere initial it with 1:

const developers = [
  { name: "ralph", language: "javascript" },
  { name: "gretchen", language: "javascript" },
  { name: "alice", language: "python" },
  { name: "mohammed", language: "javascript" },
  { name: "pat", language: "python" },
  { name: "taylor", language: "python" },
  { name: "hideo", language: "javascript" },
];
   
res = {};
developers.forEach(({ language }) => {
  if (res.hasOwnProperty(language)) {
    res[language]  = 1;
  } else {
    res[language] = 1;
  }
});
console.log(res)
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related