-1

I am struggling with outputting the duplicated letter in this function, seems a simple one, but how can I only return a duplicated letter inside the letter function.

function letter(get) {
  console.log(get) // helloworld
  const split = get.split('');
  const unique = split.some(function(v,i,a){
   console.log(v, i, a)
 });
  // expected output should be 'l'
  
}

letter('helloworld');
Frontend employee
  • 719
  • 2
  • 12
  • 26
  • This question is independent of the UI library to be used. And the real question is answered here https://stackoverflow.com/q/45245231/6281832 – Rodrigo Amaral Jul 28 '20 at 21:53

2 Answers2

1

First off: This is not a react specific question.

Second: Your current code won't produce your expected output. some only checks if any of the elments in an array pass a test and return true if any of them does, false otherwise. Your code also does not return any values, it just logs them to the console. There is also no logic in your code that performs any checks for duplicates or anything else.

Here is a your snippet modified to solve your problem.

function letter(get) {
  let checkedLetters = "";
  for (let i = 0; i < get.length; i++) {
    const letter = get[i];
    if (checkedLetters.includes(letter)) {
      console.log(letter);
      return letter;
    }
    checkedLetters += letter;
  }
  return undefined;
}

It will return the first duplicate letter in the provided string (and log it to the console), it will return undefined if there are no duplicates.

Flux
  • 410
  • 1
  • 5
  • 19
0

Just for the fun (since the question has its tag), I made a React component (see online demo) that displays the first pair of duplicate characters in a string. Notice the monospaced font in the CSS.

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

function firstDuplicate(text) {
  const arr = text.split("");
  const dictionary = {};

  for (let i = 0; i < arr.length; i++) {
    if (dictionary[arr[i]] != null) return [dictionary[arr[i]], i];
    else dictionary[arr[i]] = i;
  }

  return [null, null];
}

function highlightString(text, first, second) {
  if (first == null || second == null) return "";

  return (
    " ".repeat(first) +
    text[first] +
    " ".repeat(second - first - 1) +
    text[second]
  );
}

export default function App() {
  const [text, setText] = useState("");

  const [first, second] = firstDuplicate(text);

  const onChange = event => {
    setText(event.target.value);
  };

  return (
    <div className="App">
      <h2>Type your text and we'll find the first duplicate:</h2>

      <div
        style={{
          display: "flex",
          flexDirection: "column",
          alignItems: "flex-start"
        }}
      >
        <input type="text" onChange={onChange} value={text} />

        <input
          type="text"
          value={highlightString(text, first, second)}
          disabled
        />
      </div>
    </div>
  );
}
Rodrigo Amaral
  • 1,324
  • 1
  • 13
  • 17