Skip to content

Instantly share code, notes, and snippets.

@unilecs
Created October 8, 2017 19:32
Show Gist options
  • Save unilecs/cd776747d65a46c2623ada7f72a572dc to your computer and use it in GitHub Desktop.
Save unilecs/cd776747d65a46c2623ada7f72a572dc to your computer and use it in GitHub Desktop.
Первый уникальный символ в строке (1 способ)
function getFirstUniqueSymbol(inputStr) {
if (inputStr) {
const length = inputStr.length;
// частный случай: строка из 1го символа
if (length === 1) {
return inputStr;
}
// записываем в массив кол-во каждого символа: индекс элемента = код символа в строке
let symbolCounter = [];
for (let i=0; i<length; i++) {
const symbolCode = inputStr.charCodeAt(i);
if (symbolCounter[symbolCode]) {
symbolCounter[symbolCode] += 1;
} else {
symbolCounter[symbolCode] = 1;
}
}
// выводим первый уникальный символ
for (let i=0; i<length; i++) {
const symbolCode = inputStr.charCodeAt(i);
if (symbolCounter[symbolCode] === 1) {
return inputStr[i];
}
}
// если не нашли уникальный символ
return "";
}
return "";
}
let uniqueSymbol = getFirstUniqueSymbol("11_22_333_4_5_4_6_7");
console.info("The first unique symbol: ", uniqueSymbol !== "" ? uniqueSymbol: "not found"); // 5
@artrainbow
Copy link

const getFirstUniqueSymbol = (string) => {

if (string.length === 1) return string;

const arrIndexesOfUnicueSymbols = [...string].map(i => string.indexOf(i)).filter(i => i !== 0);
const minIndex = Math.min(...arrIndexesOfUnicueSymbols);

return [...string][minIndex];

};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment