728x90
배열 중복을 제거하는 3가지 방법을 소개합니다.
1. Set
function getSecondLargest(nums) {
// Complete the function
// 1. Set
const set = new Set(nums);
const uniqueArr = [...set];
const sortArr = uniqueArr.sort((a, b) => a-b);
let answer = sortArr[sortArr.length-2];
return answer;
}
2. indexOf(), filter()
function getSecondLargest(nums) {
// Complete the function
// 2. indexOf(), filter()
const uniqueArr = nums.filter((element, index) => {
return nums.indexOf(element) === index;
});
const sortArr = uniqueArr.sort((a, b) => a-b);
let answer = sortArr[sortArr.length-2];
return answer;
}
3. forEach(), includes()
function getSecondLargest(nums) {
// Complete the function
// 3. forEach(), includes()
let uniqueArr = [];
nums.forEach((element) => {
if(!uniqueArr.includes(element)) {
uniqueArr.push(element);
}
});
const sortArr = uniqueArr.sort((a, b) => a-b);
let answer = sortArr[sortArr.length-2];
return answer;
}
배열 중복 제거를 배운 블로그 출처:
https://hianna.tistory.com/422
'알고리즘, 자료구조 > Hackerrank' 카테고리의 다른 글
Hacker Rank JavaScript: Birthday Cake Candles (0) | 2021.05.18 |
---|