DEV Community

talent
talent

Posted on

#4.Basic algorithms problems for frontend developers.

Find a letter that occurs the most in a given sentence.

In our case example: in the phrase 'hey there my friend' the letter** e** occurs the most

const str = 'hey there my friend';

const mostFrequent = s => {
  /* declare a helper obj */
  const obj = {};

  // get a words array out of the string
  const string = s.split(' ');

  // loop over the words
  for (let word of string) {
    //loop over each letter in every word
    for (let letter of word) {
      // assign 1 if that propriety does not exist in obj
      if (!obj[letter]) obj[letter] = 1;
      // increase by one if it exists
      else obj[letter]++;
    }
  }

  //declare 2 helper variables
  let max = 0;
  let prop = '';

  // loop over the obj
  for (let key in obj) {
    /* if the value is bigger than max (which first time is 0), 
    assign the new value to max and return that key. */
    if (obj[key] > max) {
      /* reassign max to the current value 
      in the loop if the value is bigger than max */
      max = obj[key];
      //return the key of the object for the biggest value of the max
      prop = key;
    }
  }

  return prop;
};

console.log(mostFrequent(str));```


Enter fullscreen mode Exit fullscreen mode

Top comments (7)

Collapse
 
silenceleo profile image
Leo
const str = "hey there my friend";

const mostFrequent = (s) => {
  const obj = {};
  let mostFrequentLetter = "";

  const string = s.replace(/ /g, "");

  for (let letter of string) {
    !obj[letter] ? (obj[letter] = 1) : obj[letter]++;

    if (!mostFrequentLetter || obj[letter] > obj[mostFrequentLetter]) {
      mostFrequentLetter = letter;
    }
  }

  return mostFrequentLetter;
};

console.log(mostFrequent(str));

Enter fullscreen mode Exit fullscreen mode
Collapse
 
talenttinaapi profile image
talent

awesome!

Collapse
 
iccoweb profile image
iccoweb
const findMostUsedLetter = (str) => {
  const filteredStrToArr = str
    .replace(/[^a-zA-Z]/g, '')
    .split('')
    .sort()

  return filteredStrToArr.reduce((a, b, index, arr) => (
    arr.filter((v) => v === a).length >= arr.filter((v) => v === b).length
      ? a
      : b
  ), null)
}

console.log(findMostUsedLetter('hey there my friend'))
Enter fullscreen mode Exit fullscreen mode
Collapse
 
jonrandy profile image
Jon Randy ๐ŸŽ–๏ธ • Edited
const mostFrequent = s=>([...s].sort().join('').match(/(\w)\1+/g)?.sort((a,b)=>b.length-a.length)[0]||s.match(/\w/))[0]
Enter fullscreen mode Exit fullscreen mode
Collapse
 
talenttinaapi profile image
talent

simple and straight forward

Collapse
 
jonrandy profile image
Jon Randy ๐ŸŽ–๏ธ • Edited

Yup, doesn't need any explanation ๐Ÿ˜‰

Collapse
 
mt3o_23 profile image
Teodor Kulej

Hi, don't mean to discourage you, but how is this problem even remotely related to frontend?