prestudy-week2

Sunghee Kim·2022년 4월 24일

Concat
concat() 메서드는 주어진 배열에 기존 배열을 합쳐서 새로운 배열을 반환합니다.

원본 배열은 변하지 않으며 새로운 배열이나 원본 배열을 수정해도 서로 영향을 받지 않습니다.

let alphabet = ['a', 'b', 'c'];
let hangeul = ['ㄱ', 'ㄴ', 'ㄷ'];
alphabet.concat(hangeul); // [ 'a', 'b', 'c', 'ㄱ', 'ㄴ', 'ㄷ' ]

둘은 매우 비슷해보이지만 다른 결과를 반환합니다. 두번째의 경우는 배열을 3개로 인식했기 때문에 [2, 3]을 감싸는 대괄호가 사라졌습니다.
이런식으로 배열을 변수에 지정해서 인자로 넘겨줄 수도 있고, 바로 인자에서 배열을 작성해줄 수 있습니다.

const alpha = ['a', 'b', 'c'];

// 배열 2개 이어붙이기
const arr = [1, [2, 3]];
alpha.concat(arr); // [ 'a', 'b', 'c', 1, [ 2, 3 ] ]

**// 배열 3개 이어붙이기

alpha.concat(arr);
alpha.concat(1, [2, 3]); // [ 'a', 'b', 'c', 1, 2, 3 ]

const numbers = [1, 2, 3];
const numbers2 = [3, 4, 5];

numbers.concat(numbers2); // [ 1, 2, 3, 3, 4, 5 ]
요소의 중복과 상관없이 concat()은 배열을 합쳐줍니다.

Assignment

month1&2 배열을 concat()을 이용해서 하나의 배열로 합쳐주세요.
아래와 같은 결과가 나와야합니다.

[ 'July',
'Aug',
'Sept',
'Oct',
'Nov',
'Dec',
'Jan',
'Feb',
'March',
'Apr',
'May',
'June' ]
num 배열안의 요소들을 concat()을 이용해서 하나의 배열로 합쳐지게 해주세요.
아래와 같은 결과가 나와야 합니다.

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

[ 11, 12, 13, 14, 15, 16, 17, 18, 19 ]

let month1 = ['Jan', 'Feb', 'March', 'Apr', 'May', 'June'];
let month2 = ['July', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec'];
function combineMonth() {
return month2.concat(month1);
}

let num = [[11, 12, 13], [14, 15, 16], [17, 18, 19]];
function makeNewArr () {
return num[0].concat(num[1],num[2]);
}

concat응용

let array1 = [1,2,3,4,5];
let array2 = [3,4,5,6,7];
let result = array1.concat(array2);
console.log(result);
// 결과 (3,4,5 가 중복)
[
1, 2, 3, 4, 5,
3, 4, 5, 6, 7
]

let eraseDuplicates = result.filter((el,index)=>
result.indexOf(el)===index);
console.log(eraseDuplicates);
// 결과 (중복된 값이 사라짐)
[
1, 2, 3, 4,
5, 6, 7
]

filter()가 어떻게 작동됐는지 살펴봅시다.

  • indexOf(value) : 배열에서 value값의 index를 return, 없으면 -1
    value가 처음으로 몇번째나오는지.

3을 보면 3은 중복된 값으로 result.indexOf(3)은 2가 나옵니다. 처음 3은 index[2]로 조건을 만족하지만 두번째 3은 index[5]로 조건을 만족하지 않아서 통과되지 않습니다. 그래서 두번째 3은 지워지게 됩니다. 이런식으로 중복된 3, 4,5가 지워지고 하나만 남게된 것입니다!

// Assignment

let pasta = ['tomato', 'basil', 'onion','chicken'];
let pizza = ['tomato', 'cheese', 'onion','olive','beef'];
function totalIngredients () {
let ingredients=pasta.concat(pizza)
return ingredients.filter((el,index)=>
ingredients.indexOf(el)===index);
}
totalIngredients();

혹은 Set 객체를 사용해서 위와 같은 결과를 얻을 수도 있습니다.

Set객체는 요소의 값이 유일하기 위해 검사를 수행하기 때문에 중복된 값을 제거하고 싶을 때 사용합니다.

이번 세션에서는 Set을 다루지 않기 때문에 궁금하신 분들은 검색해서 공부하시는 것을 추천합니다 :)

console.log([...new Set(eraseDuplicates)]);

// 결과 (중복된 값이 사라짐)
[
1, 2, 3, 4,
5, 6, 7
]

1) Remove duplicates from an array using a Set
A Set is a collection of unique values. To remove duplicates from an array:

First, convert an array of duplicates to a Set. The new Set will implicitly remove duplicate elements.
Then, convert the set back to an array.
The following example uses a Set to remove duplicates from an array:

let chars = ['A', 'B', 'A', 'C', 'B'];
let uniqueChars = [...new Set(chars)];

console.log(uniqueChars);
Code language: JavaScript (javascript)
Output:

[ 'A', 'B', 'C' ]

profile
개발하는 스트롱맘

0개의 댓글