Array의 기타 메서드 정리

수경, Sugyeong·2021년 9월 3일
0

JavaScript

목록 보기
11/18
post-thumbnail

  • slice()
  • filter()
  • include()
  • concat()

  • 🥝 slice()

    slice 메서드는 특정 배열에서 인덱스로 선택된 요소들을 새로운 배열로 반환한다. 또한 splice 메서드와는 다르게 원본(original) 배열을 바꾸지 않기 때문에 slice 메서드를 적용한 새로운 변수를 선언해주어야 한다.

    slice 메서드 구조

    array.slice(start, end);
    • start : 시작점 인덱스
    • end : 끝점 인덱스
      * 메서드의 필요에 따라 최소 1개의 인자를 사용할 수 있다.

    예제

    let color = ['yellow', 'green', 'pink', 'blue'];
    let sunFlower = color.slice(0, 2);
    
    console.log(color);	// ["yellow", "green", "pink", "blue"]
    console.log(sunFlower);	// ["yellow", "green"]

    인자에 음수가 들어가는 경우도 있다. 이런 경우에는 끝에서부터 해당하는 숫자 만큼의 요소를 새로운 배열에 담아서 반환하게 된다.

    var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
    var myBest = fruits.slice(-4, -3);
    
    console.log(myBest);	// ["Orange"]

    문제 1)

    • 숫자 2를 구하기
    function saveNumberTwo(prisoners) {
      let temp = prisoners.slice(-2, -1);	//	[1,2]
      // slice 메서드의 괄호 안에 음수만 넣어주세요
      let answer = temp[0][1]	//	2 (인덱스로 값을 구함.)
      // 변수 answer에 특정한 값을 대입해주세요.
      return answer;
    }
    saveNumberTwo([0, 1],[1,2],[0,0]);

    🥝 filter()

    메서드 이름 그대로 필요한 데이터만을 걸러내어 새로운 배열을 반환한다. slice() 메서드와 마찬가지로 원본(original) 배열을 바꾸지 않으며, 조건에 부합하는 요소가 없다면 빈 배열을 반환한다.

    filter 메서드의 구조

    arr.filter(callback(element[, index[, array]])[, thisArg])
    • callback : 각 요소를 시험할 함수. true를 반환하면 요소를 유지하고, false를 반환하면 버린다. callback 은 다음 세 가지 인자를 받는다.
    1. element : 현재 배열에서 처리되고 있는 요소
    2. index(optional) : 현재 배열에서 처리되고 있는 요소의 인덱스
    3. array(optional) : filter를 호출한 array
    • thisArg(optional) : callbackFn을 실행할 때 this로 사용하는 값

    반환되는 값으로는 조건에 통과된 요소들로 이루어진 새로운 배열이 된다. 만약 어떠한 요소도 조건에 부합하지 않는다면 빈 배열이 반환된다.

    filter 메서드는 3가지 방식으로 작성할 수 있다.

    1. Arrow function
    filter((element, index, array) => { ... } )	// index와 array는 없을 수도 있음.
    list.filter(word => word.length >= 6);		// 예시

    1. Callback function
    filter(callbackFn, thisArg)	// thisArg는 없을 수도 있음.
    list.filter(function(word){
      return word.length >= 6 ;
    })				// 예시

    1. Inline callback function
    filter(function callbackFn(element, index, array) { ... }, thisArg)
    // index, array 와 thisArg는 없을 수도 있음.
    function filterCallbackFunction(word){
    	return word.length >= 6;
    };
    
    list.filter(filterCallbackFunction);	// 예시

    예제

    filter 메서드가 실행되는 구조를 알기 위해서 다음과 같은 예제를 사용해본다.

    let testArray = [1,2,3,4,5];
    let newArray = testArray.filter(function(element, index, array){
        console.log(element);
        console.log(index);
        console.log(array);
        })
    //
    1		// 현재 배열에서 처리되고 있는 인자값
    0		// 현재 배열에서 처리되고 있는 인자값의 인덱스
    [1, 2, 3, 4, 5]	// filter에서 호출한 배열
    2
    1
    [1, 2, 3, 4, 5]
    3
    2
    [1, 2, 3, 4, 5]
    4
    3
    [1, 2, 3, 4, 5]
    5
    4
    [1, 2, 3, 4, 5]

    배열이 3이하인 값만 추출하여 새 배열을 만들어본다.

    let testArray = [1,2,3,4,5];
    let newArray = testArray.filter(function(element){
        return element <= 3
        })
    
    console.log(newArray);	// [1, 2, 3]
    var array = [1, 0, 3, "puppies", false, 5, 4, 7];   
    var output = array.filter((element)=>{ return element > 4; });
    // 5,7
    • fruits 라는 배열이 있다. 'ap'가 들어간 과일들로 이루어진 새로운 배열을 filter()를 이용하여 반환한다. (includes() 를 사용한다.)

    1) 첫 번째 방법

    let fruits = ['apple', 'banana', 'grapes', 'mango', 'orange'];
    
    function filtered (el) {
      let result = fruits.filter((el) => el.includes('ap'));
      return result;
    }
    
    console.log(filtered(fruits))	// ["apple", "grapes"]

    2) 두 번째 방법

    let fruits = ['apple', 'banana', 'grapes', 'mango', 'orange'];
    
    function filtered (el) {
      let result = fruits.filter(function(el) {return el.includes('ap')});
      return result;
    }
    
    console.log(filtered(fruits))	// ["apple", "grapes"]
    • courses 라는 배열이 있다. level이 'hard'인 과목들로만 이루어진 새로운 배열을 filter()를 이용하여 반환한다.

    1) 첫 번째 방법

    let courses = [
    {level:'easy', subject: "English" }, 
    {level:'hard', subject: "Mathmatic" }, 
    {level:'medium', subject: "Literature" }, 
    {level:'hard', subject: "Science" }, 
    {level:'medium', subject: "Socialogy" }
    ];
    
    function filtered(el) {
      let result = courses.filter((el) => el.level === 'hard');
      return result;
    }
    
    console.log(filtered(courses))
    // 
    [[object Object] {
      level: "hard",
      subject: "Mathmatic"
    }, [object Object] {
      level: "hard",
      subject: "Science"
    }]

    2) 두 번째 방법

    let courses = [
    {level:'easy', subject: "English" }, 
    {level:'hard', subject: "Mathmatic" }, 
    {level:'medium', subject: "Literature" }, 
    {level:'hard', subject: "Science" }, 
    {level:'medium', subject: "Socialogy" }
    ];
    
    function filtered(el) {
      let result = courses.filter(function(el){
        return el.level === 'hard'});
      return result;
    }
    
    console.log(filtered(courses))
    • 두 가지 배열을 새로운 배열로 반환할 때 중복된 값을 제거한다.
    let pasta = ['tomato', 'basil', 'onion', 'chicken'];
    let pizza = ['tomato', 'cheese', 'onion', 'olive', 'beef'];
    
    function totalIngredients () {
      let together = pasta.concat(pizza);
      // ['tomato', 'basil', 'onion', 'chicken', 'tomato', 'cheese', 'onion', 'olive', 'beef']
      let eraser = together.filter((el, index) => together.indexOf(el)===index);
      return eraser
    }

    여기서 indexOf 메서드는 주어진 요소가 배열에서 발견될 수 있는 첫 번째 인덱스를 리턴하거나 존재하지 않는 경우 -1을 리턴한다는 특징이 있다. 첫 번째로 등장한 'tomato'는 indexOf() 값이 0이 나온다. 하지만 두 번째로 등장한 'tomato'의 index 값은 4인데 indexOf 로 돌리면 0이라는 결과가 나오기 때문에 서로 조건을 만족하지 않아서 통과되지 않는다. 그래서 두 번째로 나온 'tomato'는 지워지게 된다.


    🥝 includes()

    include() 메서드는 배열에 항목 중 특정 값이 포함되어 있는지 여부를 확인하여 적절하게 true 또는 false를 반환한다.

    include 메서드의 구조

    includes(searchElement)
    includes(searchElement, fromIndex)
    • searchElement : 찾고자 하는 값
    • fromIndex(optional) : 배열에서 searchElement를 찾기 시작하는 위치
      * 문자나 문자열을 비교할 때, includes()는 대소문자를 구분한다.

    예제

    let stationary = ['ruler', 'pencil', 'eraser', 'scissor', 'note']
    
    let result = stationary.includes('eraser')
    console.log(result)		// true
    let stationary = ['ruler', 'pencil', 'eraser', 'scissor', 'note']
    
    let result = stationary.includes('eraser', 3)
    console.log(result)		// false

    fromIndex가 음수일 때 계산된 인덱스는 searchElement를 찾기 시작할 배열의 위치로 사용되도록 계산된다. 만약 계산된 인덱스가 0보다 작거나 같으면 전체 배열이 검색된다.

    let stationary = ['ruler', 'pencil', 'eraser', 'scissor', 'note']
    
    let result = stationary.includes('eraser', -100)
    console.log(result)		// true
    let stationary = ['ruler', 'pencil', 'eraser', 'scissor', 'note']
    
    let result = stationary.includes('eraser', -2)
    console.log(result)		// false

    🥝 concat()

    concat() 메서드는 2개 혹은 그 이상의 배열들을 합칠 때 사용한다. 이 메서드는 기존 배열의 형태를 바꾸지 않으며 새로운 배열을 반환한다.

    concat() 메서드의 구조

    concat()
    concat(value0)
    concat(value0, value1)
    concat(value0, value1, ... , valueN)
    • valueN(optional) : 새 배열로 연결할 배열 또는 값

    concat은 메서드를 호출한 배열 뒤에 각 인수를 순서대로 붙여 새로운 배열을 만든다. 호출한 인자가 배열이면 그 구성요소가 순서대로 붙고, 배열이 아니면 인자 자체가 붙는다.

    concat은 this나 인자로 넘겨진 배열의 내용을 바꾸지 않고, 대신 주어진 배열을 합친 뒤 사본을 반환한다.

    예제

    배열을 2개 이어 붙이기

    const letters = ['a', 'b', 'c'];
    
    const arr = [1, [2, 3]];
    
    const alphaNumeric = letters.concat(arr);
    
    console.log(alphaNumeric);	// ["a", "b", "c", 1, [2, 3]]

    배열 3개 이어붙이기
    배열을 3개로 인식했기 때문에 [2, 3]을 감싸는 대괄호가 사라진다.

    const letters = ['a', 'b', 'c'];
    
    const alphaNumeric = letters.concat(1, [2, 3]);
    
    console.log(alphaNumeric);
    // results in ['a', 'b', 'c', 1, 2, 3]
    const num1 = [[1]];
    const num2 = [2, [3]];
    
    const numbers = num1.concat(num2);
    
    console.log(numbers);
    // results in [[1], 2, [3]]
    
    // modify the first element of num1
    num1[0].push(4);
    
    console.log(numbers);
    // results in [[1, 4], 2, [3]]

    중복된 숫자나 글자를 가진 배열을 합쳐도 중복된 결과가 사라지지 않는다.

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

    문제 1)

    • month1&2 배열을 concat()을 이용하여 하나의 배열로 합치기
    let month1 = ['Jan', 'Feb', 'March', 'Apr', 'May', 'June'];
    let month2 = ['July', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec'];
    
    // 아래의 함수를 완성해주세요.
    function combineMonth() {
      let result = month2.concat(month1);
      return result
    }

    문제 2)

    • num 배열안의 요소들을 concat()을 이용해서 하나의 배열로 합치기
      (array에서 index로 접근)
    let num = [[11, 12, 13], [14, 15, 16], [17, 18, 19]]; 
    
    //아래의 함수를 완성해주세요. 
    function makeNewArr () {
      let newNum = num[0].concat(num[1], num[2]);
      return newNum
    }	//	[ 11, 12, 13, 14, 15, 16, 17, 18, 19 ]

    <출처>
    w3schools
    비비로그
    MDN
    aljjabaegi
    삽질중인 개발자
    betterprogramming

    0개의 댓글