Created
May 11, 2018 12:46
-
-
Save bsa7/a6deb329e88a30484b06f1ba4f09d196 to your computer and use it in GitHub Desktop.
Найти индексы похожих элементов в массиве
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var arr = ["abc", "bac","abc", "d","et","d","et","zzz"]; | |
/** | |
* Сравнивает две строки на похожесть | |
* @param {String} sample1 | |
* @param {String} sample2 | |
*/ | |
const compare = (sample1, sample2) => { | |
return sample1.length == sample2.length && sample1.split('').filter((letter) => sample2.includes(letter)).length > 0 | |
} | |
/** | |
* Находит похожие элементы в массиве для заданного элемента массива | |
* @param {Array} arr | |
* @param {Number} exampleIndex | |
*/ | |
const findSimilar = (arr, exampleIndex) => { | |
const indexes = [] | |
arr.forEach((item, index) => { | |
if (compare(item, arr[exampleIndex])) { | |
indexes.push(index) | |
} | |
}) | |
if (indexes.length == 1) { | |
return undefined | |
} | |
return indexes | |
} | |
/** | |
* Собирает итоговую статистику для массива, находя индексы похожих элементов | |
* @param {Array} arr | |
*/ | |
const stat = (arr) => { | |
let similarIndexesUsed = [] | |
arr.forEach((item, index) => { | |
if (!similarIndexesUsed.includes(index)) { | |
const similarIndexes = findSimilar(arr, index) | |
if (similarIndexes) { | |
similarIndexesUsed = similarIndexesUsed.concat(similarIndexes) | |
console.log(`${item}: ${similarIndexes.join(', ')}`) | |
} | |
} | |
}) | |
} | |
stat(arr) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment