정수 배열 numbers에서 두 개의 수를 뽑아 더해서 만들 수 있는 모든 수를 배열에 오름차순으로 담아 return하는 solution 함수 구하기
중복되는 숫자를 지우는 것이 핵심
function solution(numbers) {
let answer = [];
for(let i=0; i<numbers.length; i++) {
for(let j=i+1; j<numbers.length; j++) {
let num = numbers[i]+numbers[j];
if(answer.indexOf(num)===-1) answer.push(num);
}
}
return answer.sort((a,b)=> a-b);
}
let arr = [2,1,3,4,1];
console.log(solution(arr)); // [ 2, 3, 4, 5, 6, 7 ]
array.indexOf(value)를 사용
: 해당 값의 인덱스가 없다면 -1을 반환, 즉 배열 안에 해당 값이 존재 X
for문을 돌면서 해당 값이 존재하지 않을 때만 배열에 담아준다. 이미 존재하는 값이라면 인덱스가 존재하기 때문에 조건문을 충족시키지 못함
오름차순 정렬을 위해 array.sort((a,b) => a-b) 코드 사용
: 숫자의 경우, 유니코드로 인식하기 때문에 꼭 콜백함수를 사용해야 한다.
function solution(numbers) {
const temp = [];
for(let i=0; i<numbers.length; i++){
for(let j=i+1; j<numbers.length; j++){
temp.push(numbers[i]+numbers[j]);
}
}
const answer = [...new Set(temp)].sort((a,b) => a-b);
return answer;
}
let arr = [2,1,3,4,1];
console.log(solution(arr)); // [ 2, 3, 4, 5, 6, 7 ]
Set 객체
- 삽입 순서대로 요소를 순회하며 자료형에 관계 없이 유일한 값을 저장
- 하나의 Set 내 어떤 값은 유일한 값, 중복된 값이 존재하지 X
const set1 = new Set([1,2,3,3,2,1,2,2]) console.log(set1); // Set(3) {1, 2, 3}