Javascript Basic [Array - replit 21: concat]

Seong Ho Kim·2023년 9월 30일
0

Javascript Basic - replit

목록 보기
21/41
post-thumbnail

Javascript Assignment 21 - [Array 배열]

1) Array - concat 메서드

Assignment

concat() 메서드는 주어진 배열에 기존 배열을 합쳐서 새로운 배열을 반환합니다.
const alphabet = ['a', 'b', 'c'];
const hangeul = ['ㄱ', 'ㄴ', 'ㄷ'];
alphabet.concat(hangeul); // ['a', 'b', 'c', 'ㄱ', 'ㄴ', 'ㄷ']

만약 중복된 숫자나 글자를 가진 배열을 합친다면 어떤 결과가 나올까요? 
중복된 결과가 사라질까요?

const numbers = [1, 2, 3];
const numbers2 = [3, 4, 5];
numbers.concat(numbers2);      // [1, 2, 3, 3, 4, 5]

그렇지 않고 배열 요소 그대로 합쳐지는 것을 확인할수 있습니다.
이때, 중복된 데이터 요소를 제거하기 위해선 filter 메서드를 이용해야 합니다.

Assignment
1번 문제) 
month1&2 배열을 concat()을 이용해서 하나의 배열로 합쳐주세요.
1번 최종 결과값은 다음과 같이 나와야 합니다
["Jan", "Feb", "March", "Apr", "May", "June", "July", "Aug", "Sept", "Oct", "Nov", "Dec"]
  
2번 문제)
num 배열안의 요소들을 concat()을 이용해서 하나의 배열로 합쳐지게 해주세요.
2번 최종 결과값은 다음과 같이 나와야 합니다
[11, 12, 13, 14, 15, 16, 17, 18, 19]

(힌트: array에서 index로 접근)

Assignment - Javascript Code

// 1
// 아래의 함수를 완성해주세요.
function combineMonth() {
  const month1 = ['Jan', 'Feb', 'March', 'Apr', 'May', 'June'];
  const month2 = ['July', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec'];
  const resultMonth = month1.concat(month2);
  return resultMonth;
}
const result = combineMonth();
console.log(result); // ["Jan", "Feb", "March", "Apr", "May", "June", "July", "Aug", "Sept", "Oct", "Nov", "Dec"]

// 2
//아래의 함수를 완성해주세요.
function makeNewArr() {
  const num = [[11, 12, 13], [14, 15, 16], [17, 18, 19]];
  const resultNum = num[0].concat(num[1]).concat(num[2]);

  return resultNum;
}
const result = makeNewArr();
console.log(result); // [11, 12, 13, 14, 15, 16, 17, 18, 19]

Personal Assignment

1. 현재 num1, num2 변수에 서로 중복되는 데이터 값이 있습니다.
중복되는 데이터 값을 찾아서 제거후 나머지 배열 요소를 합쳐서 출력해주세요

2. 현재 numArr 변수에 중첩된 배열요소에 중복되는 데이터 값이 있습니다.
중복되는 데이터 값을 찾아서 제거후 나머지 배열 요소를 합쳐서 출력해주세요

힌트)
- num 변수에 있는 배열 요소를 합쳐주세요.
- filter 메서드를 이용해 indexOf를 사용해서 중복된 데이터를 제거하셔야 합니다. 

Personal Assignment - Javascript Code

// 1)
function numNewArr() {
  const num1 = [1,2,3,4,5]
  const num2 = [5,6,7,8,9]
  
  const merged = num1.concat(num2);
  const filters = merged.filter((item, pos) => (merged.indexOf(item) === (pos)));

  return filters;
}
const result1 = numNewArr();
console.log(result1); // [1,2,3,4,5,6,7,8,9]

// 2)
const newNumArr = () => {
  let numArr = [[1, 2, 3], [4, 5, 6], [6, 7, 8, 9, 10]]
  let numArrResult = numArr[0].concat(numArr[1]).concat(numArr[2])
  let merged = numArrResult.filter((item, pos) => (numArrResult.indexOf(item) === (pos)))
  return merged;
}
const result2 = newNumArr();
console.log(result2); // [ 1, 2, 3, 4,  5, 6, 7, 8, 9, 10]
profile
삶을 개선하기 위해 노력하는 Junior UIUX Designer 입니다 😊

0개의 댓글