skip to Main Content

I am new to react. I am learning by coding an anagram problem.
I am trying to display the below result in the browser.
[[‘silent’, ‘listen’], [‘test’] , [‘another’]] but I am seeing this result. —> [ "s", "i", "l", "e", "n", "t" ] can you let me know how to display the expected result.
providing the sandbox and code below

import "./styles.css";
import React, { useState, useEffect } from "react";

export default function App() {
  const [words, setWords] = ["silent", "listen", "test", "another"];
  const [groupedAnangrams, setGroupedAnangrams] = useState([]);

  useEffect(() => {
    const groupAnangrams = (words) => {
      const anangramGroups = {};
      const result = [];
      for (const word of words) {
        const sortedWord = word.split("").sort().join("");

        if (anangramGroups[sortedWord]) {
          anangramGroups[sortedWord].push(word);
        } else {
          anangramGroups[sortedWord] = word;
        }
      }
      for (const group in anangramGroups) {
        result.push(anangramGroups[group]);
      }

      return result;
    };

    const grouped = groupAnangrams(words);
    setGroupedAnangrams(grouped);
  }, [words]);
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>{JSON.stringify(groupedAnangrams, null, 2)}</h2>
    </div>
  );
}

2

Answers


  1. You can try this one.

    import React, { useState, useEffect } from 'react';
    
    export default function App() {
      const [words] = useState(['silent', 'listen', 'test', 'another']);
      const [groupedAnagrams, setGroupedAnagrams] = useState([]);
    
      useEffect(() => {
        const groupAnagrams = (words) => {
          const anagramGroups = {};
          const result = [];
          
          for (const word of words) {
            const sortedWord = word.split('').sort().join('');
    
            if (anagramGroups[sortedWord]) {
              anagramGroups[sortedWord].push(word);
            } else {
              anagramGroups[sortedWord] = [word]; // --> diff here
            }
          }
    
          for (const group in anagramGroups) {
            result.push(anagramGroups[group]);
          }
    
          return result;
        };
    
        const grouped = groupAnagrams(words);
        setGroupedAnagrams(grouped);
      }, [words]);
    
      return (
        <div className='App'>
          <h1>Hello CodeSandbox</h1>
          <h2>{JSON.stringify(groupedAnagrams, null, 2)}</h2>
        </div>
      );
    }
    
    

    It’s based on your code.

    Login or Signup to reply.
  2. Please see below for observations, code corrections and suggestions.

    A full list of the corrected code with test run results is enclosed below. It is basically your own code, the change is only in the corrected part.

    a) an unintended code

    The below code is de-structuring the given array and assigns the first two string values into the the two variables on the left. Therefore the variables words and setWords will have the values "silent" and "listen". This may not be the action intended over here. Therefore, please review this code and correct it to the best possible way.

    const [words, setWords] = ["silent", "listen", "test", "another"];
    

    One of the possible ways to correct the same is given below. The below code is intended to declare and initialise the variable words with the given array. Please note that the variable words over here is not a state, on the contrary, it is a local variable which does not survive a render. However it would suffice for this case. This correction will be well understood when you see below the corrected code in action.

    const words = ["silent", "listen", "test", "another"];
    

    b) review the useEffect dependency array

    The following code sets the dependency array with the variable words. And it is expected that every change in the variable words should invoke useEffect. As long as the list of words is hard-coded in the component as it is in this case, this variable will not change. It will get initial values, and will remain unchanged. Therefore this dependency may be reviewed.

     useEffect(() => {
        const groupAnangrams = (words) => {
         ...
        setGroupedAnangrams(grouped);
      }, [words]);
    

    One of the possible revisions is given below. The below code sets an empty dependency array. It means that the code inside useEffect will run only once – that will be on mounting the component or the component will appear for the first time. The objective of this revision will also be well understood when you see the code in action.

     useEffect(() => {
        const groupAnangrams = (words) => {
         ...
        setGroupedAnangrams(grouped);
      }, []);
    

    c) a logical error

    The below code, sets the word against the property. The word is a string over here. However this is not sufficient for the intended output. The output asks for it to be a string inside an array. Therefore this statement requires correction.

    anangramGroups[sortedWord] = word;
    

    The correction is this: Please enclose the string within an array. The following code does more than the previous one. The code sets a string enclosed in an array.

    anangramGroups[sortedWord] = [word];
    

    d) a cascading issue

    The below code is intended to add more string values into the array. However, it will work only if the existing value is an array. Therefore the correction we applied above is very essential, it will make this code also working. Without that correction, this statement will fail as push is a method available only on arrays not on strings.

    anangramGroups[sortedWord].push(word);
    

    Corrected code – full listing

    app.js

    // The corrected statements have been commented 
    // with line numbers as line 1, line 2 and line 3.
    
    import React, { useState, useEffect } from 'react';
    
    export default function App() {
      const words = ['silent', 'listen', 'test', 'another']; // line 1
      const [groupedAnangrams, setGroupedAnangrams] = useState([]);
    
      useEffect(() => {
        const groupAnangrams = (words) => {
          const anangramGroups = {};
          const result = [];
          for (const word of words) {
            const sortedWord = word.split('').sort().join('');
    
            if (anangramGroups[sortedWord]) {
              anangramGroups[sortedWord].push(word);
            } else {
              anangramGroups[sortedWord] = [word]; // line 3
            }
          }
          for (const group in anangramGroups) {
            result.push(anangramGroups[group]);
          }
    
          return result;
        };
    
        const grouped = groupAnangrams(words);
        setGroupedAnangrams(grouped);
      }, []); // line 2
      return (
        <div className="App">
          <h1>Hello CodeSandbox</h1>
          <h2>{JSON.stringify(groupedAnangrams, null, 2)}</h2>
        </div>
      );
    }
    

    Test run

    Application on loaded state

    Browser display - application on loaded state

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search