Created
August 28, 2020 07:18
-
-
Save hmmhmmhm/f3a47339d694d666617ea38e0ea12722 to your computer and use it in GitHub Desktop.
checkDuplicatesInArray 타입스크립트 배열 안의 같은 값 찾아내기
This file contains hidden or 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
| /** | |
| * 배열 안의 겹치는 값을 찾아냅니다. | |
| * @example | |
| * const some = ['1', '2', '3', '4', '5', '1', '1'] | |
| * console.log(checkDuplicatesInArray(some)) | |
| * // { '1': [ 0, 5, 6 ] } | |
| * @param items | |
| * @param isNeedFirstValue | |
| */ | |
| export const checkDuplicatesInArray = ( | |
| items: any[], | |
| isNeedFirstValue = true | |
| ) => { | |
| const checked: any[] = [] | |
| const duplicates: { | |
| [key in string]: number[] | |
| } = {} | |
| // * 중복되는 값들을 찾아냅니다. | |
| for (let i = 0; i < items.length; i++) { | |
| const currentValue = items[i] | |
| // * 중복값이 있으면 기록합니다. | |
| if (checked.indexOf(currentValue) != -1) { | |
| if (!duplicates[String(currentValue)]) | |
| duplicates[String(currentValue)] = [] | |
| duplicates[String(currentValue)].push(i) | |
| } | |
| checked.push(currentValue) | |
| } | |
| // * 처음 값도 찾아냅니다. | |
| if (isNeedFirstValue) { | |
| for (let key of Object.keys(duplicates)) | |
| duplicates[key].unshift(items.indexOf(key)) | |
| } | |
| return duplicates | |
| } |
hmmhmmhm
commented
Aug 28, 2020
Author

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