Replit.JavaScript 배열-12. concat응용

younghyun·2021년 12월 30일
0
  • 중복 없는 배열 결합 ( concat, filter 응용 )

  • 배열 결합

    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
    ]

    3은 중복된 값으로 result.indexOf(3)은 2가 나옴. 처음 3은 index[2]로 조건을 만족하지만, 두번 째 3은 index[5]로 조건을 만족하지 않아서 통과되지 않음. 그래서 두번 째 3은 지워짐.

    혹은 Set객체( 요소 값이 유일하기 위해 검사 수행하기 때문에 중복된 값 제거하고 싶을 때 사용 )를 사용해서 위와 같은 결과를 얻을 수 있음.

Assignment
파스타와 피자의 재료가 배열로 나타나있습니다. 위의 코드를 참고해서 중복된 재료를 뺀 전체 재료의 배열 한 개를만들어주세요.

아래와 같은 결과가 나와야 합니다.

// 중복된 재료를 뺀 전체 재료
[ 'tomato', 'basil', 'onion', 'chicken', 'cheese', 'olive', 'beef' ]

// Assignment
let pasta = ['tomato', 'basil', 'onion','chicken'];

let pizza = ['tomato', 'cheese', 'onion','olive','beef'];


// 아래 함수를 작성해주세요. 
function totalIngredients () {
  let result = pasta.concat(pizza)

  let eraseDuplicates = result.filter((el, index) => result.indexOf(el)===index);

  return eraseDuplicates
}

console.log(totalIngredients())

module.exports = { totalIngredients };
profile
선명한 기억보다 흐릿한 메모

0개의 댓글