Home > Back-end >  I need help understanding a couple lines of code
I need help understanding a couple lines of code

Time:08-27

can someone help me understand what is happening on this line:

chars[char] = (chars[char] || 0)   1;

and on line:

.filter((char) => char[1] > 1).map((char) => char[0]);
/* FULL CODE */
const getRepeatedChars = (str) => {
  const chars = {};
  for (const char of str) {
    chars[char] = (chars[char] || 0)   1;
  }
  return Object.entries(chars)
    .filter((char) => char[1] > 1)
    .map((char) => char[0]);
};

console.log(getRepeatedChars("aabbkdndiccoekdczufnrz"));

CodePudding user response:

chars[char] = (chars[char] || 0)   1;

This adds 1 to the value of chars[char]. If there's no element in the object with key char, the value of chars[char] will be undefined. undefined || 0 is 0; adding 1 to this initializes the element to 1 the first time a particular character is encountered.

Object.entries(chars)
.filter((char) => char[1] > 1).map((char) => char[0]);

Object.entries(chars) returns an array whose elements are nested arrays of the form [key, value], the keys and values of the chars object. The keys are the characters in the strings, the values are the repetition counts. So char[1] > 1 tests if the character appeared more than once, and filter() returns an array where this is true. Then .map() returns char[0], which is the character. So this returns the characters that appeared more than once.

  • Related