Skip to content

Instantly share code, notes, and snippets.

@hmmhmmhm
Created August 28, 2020 07:18
Show Gist options
  • Select an option

  • Save hmmhmmhm/f3a47339d694d666617ea38e0ea12722 to your computer and use it in GitHub Desktop.

Select an option

Save hmmhmmhm/f3a47339d694d666617ea38e0ea12722 to your computer and use it in GitHub Desktop.
checkDuplicatesInArray 타입스크립트 배열 안의 같은 값 찾아내기
/**
* 배열 안의 겹치는 값을 찾아냅니다.
* @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

Copy link
Copy Markdown
Author

스크린샷 2020-08-28 오후 4 17 00

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