ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • JavaScript의 Array 관련 함수들
    JavaScript 2020. 10. 11. 12:17
    반응형

    자바스크립트의 알고리즘 공부를 하다보면 Array 관련 메소드들을 활용이 비일비재하다. 가장 자주 사용되고 기본적으로 알고 있어야 할 prototype 함수들을 정리해보고자 한다.

     

     

    Array.from()

    console.log(Array.from('foo'));
    // expected output: Array ["f", "o", "o"]
    
    console.log(Array.from([1, 2, 3], x => x + x));
    // expected output: Array [2, 4, 6]
    
    console.log(Array.from({ a: '1', b: '2' }));
    // [] : object는 빈 배열로 리턴된다.
    
    let obj = { a: '1', b: '2' };
    Array.from(Object.keys(obj));
    // ["a", "b"]
    Array.from(Object.values(obj));
    // ["1", "2"]

     

     

    Array.of()

    Array.of(7);       // [7] 
    Array.of(1, 2, 3); // [1, 2, 3]
    Array.of(undefined); // [undefined]
    
    Array(7);          // [ , , , , , , ]
    Array(1, 2, 3);    // [1, 2, 3]

     

    Array.prototype.concat()

    기존배열을 변경하지 않습니다.
    추가된 새로운 배열을 반환합니다.
    중첩 배열 내부로 재귀하지 않습니다.

    const alpha = ['a', 'b', 'c'];
    const numeric = [1, 2, 3];
    
    alpha.concat(numeric);
    // 결과: ['a', 'b', 'c', 1, 2, 3]
    
    let b = [1, 2, 3];
    let c = [4, 5, [6, 7]];
    b.concat(c);
    // [1, 2, 3, 4, 5, [6, 7]]

     

    Array.prototype.fill()

    배열의 시작 인덱스부터 끝 인덱스의 이전까지 정적인 값 하나로 채웁니다.

     

    var array1 = [1, 2, 3, 4];
    
    // fill with 0 from position 2 until position 4
    console.log(array1.fill(0, 2, 4));
    // expected output: [1, 2, 0, 0]
    
    // fill with 5 from position 1
    console.log(array1.fill(5, 1));
    // expected output: [1, 5, 5, 5]
    
    console.log(array1.fill(6));
    // expected output: [6, 6, 6, 6]

     

    Array.prototype.filter()

    주어진 함수의 테스트를 통과하는 모든 요소를 모아 새로운 배열로 반환합니다.
    원본 배열은 그대로 유지.

     

    var words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
    
    const result = words.filter(word => word.length > 6);
    
    console.log(words);
    console.log(result);
    // Array ["spray", "limit", "elite", "exuberant", "destruction", "present"]
    // Array ["exuberant", "destruction", "present"]

     

    Array.prototype.find()

    주어진 판별 함수를 만족하는 첫 번째 요소의 값을 반환합니다. 그런 요소가 없다면 undefined를 반환합니다.

    var array1 = [5, 12, 8, 130, 44];
    
    var found = array1.find(function(element) {
        return element > 10;
    });
    
    console.log(found);
    // expected output: 12
    
    const inventory = [
        {name: 'apples', quantity: 2},
        {name: 'bananas', quantity: 0},
        {name: 'cherries', quantity: 5}
    ];
    
    const result = inventory.find(fruit => fruit.name === 'cherries');
    
    console.log(result) // { name: 'cherries', quantity: 5 }

     

    Array.prototype.forEach()

    주어진 함수를 배열 요소 각각에 대해 실행합니다.
    forEach()는 배열을 변형하지 않습니다. 그러나 callback이 변형할 수는 있습니다.
    예외를 던지지 않고는 forEach()를 중간에 멈출 수 없습니다.

     

    Array.prototype.includes()

    includes() 메서드는 배열이 특정 요소를 포함하고 있는지 판별합니다.

    arr.includes(valueToFind[, fromIndex])
    • valueToFind : 탐색할 요소. 문자나 문자열을 비교할 때, includes()는 대소문자를 구분합니다.
    • fromIndex (Optional) : 이 배열에서 searchElement 검색을 시작할 위치입니다. 음의 값은 array.length + fromIndex의 인덱스를 asc로 검색합니다. 기본값은 0입니다.
    // array length is 3
    // fromIndex is -1
    // computed index is 3 + (-1) = 2
    
    var arr = ['a', 'b', 'c'];
    
    arr.includes('a', -1); // false
    arr.includes('a', -2); // false
    arr.includes('a', -3); // true
    
    var ary = [
        { a: 'a', b: 'b'},
        { a: 'aa', b: 'bb'}
    ];
    ary.includes({ a: 'a', b: 'b'}); // false. 객체는 확인 불가

     

     

    Array.prototype.keys()

    keys() 메서드는 배열의 각 인덱스를 키 값으로 가지는 새로운 Array Iterator 객체를 반환합니다.

     

    Array.prototype.map()

    map() 메서드는 배열 내의 모든 요소 각각에 대하여 주어진 함수를 호출한 결과를 모아 새로운 배열을 반환합니다.
    map이 처리할 요소의 범위는 첫 callback을 호출하기 전에 정해집니다. map이 시작한 이후 배열에 추가되는 요소들은 callback을 호출하지 않습니다.

    var array1 = [1, 4, 9, 16];
    
    // pass a function to map
    const map1 = array1.map(x => x * 2);
    
    console.log(map1); // expected output: Array [2, 8, 18, 32]
    console.log(array1); // Array [1, 4, 9, 16] 원본 유지
    
    // 아래 라인을 보시면...
    ['1', '2', '3'].map(parseInt);
    // 결과를 [1, 2, 3] 으로 기대할 수 있습니다.
    // 그러나 실제 결과는 [1, NaN, NaN] 입니다.
    
    // parseInt 함수는 보통 하나의 인자만 사용하지만, 두 개를 받을 수 있습니다.
    // 첫 번째 인자는 변환하고자 하는 표현이고 두 번째는 숫자로 변환할 때 사용할 진법입니다.
    // Array.prototype.map은 콜백에 세 가지 인자를 전달합니다.
    // 배열의 값, 값의 인덱스, 그리고 배열
    // 세 번째 인자는 parseInt가 무시하지만 두 번째 인자는 아닙니다.

     

    Array.prototype.reduce()

    reduce() 메서드는 배열의 각 요소에 대해 주어진 리듀서(reducer) 함수를 실행하고, 하나의 결과값을 반환합니다.

    [0, 1, 2, 3, 4].reduce(function(accumulator, currentValue, currentIndex, array) {
        return accumulator + currentValue;
    });

     

    Array.prototype.shift()

    shift() 메서드는 배열에서 첫 번째 요소를 제거하고, 제거된 요소를 반환합니다. 이 메서드는 배열의 길이를 변하게 합니다.

     

    Array.prototype.slice()

    slice() 메서드는 어떤 배열의 begin부터 end까지(end 미포함)에 대한 얕은 복사본을 새로운 배열 객체로 반환합니다. 원본 배열은 수정되지 않습니다.

    var animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];
    
    const ary1 = animals.slice(2);
    const ary2 = animals.slice(2, 4)
    
    console.log(animals);
    console.log(ary1);
    console.log(ary2);
    
    animals[0] = 'aaaaa';
    console.log(animals);
    console.log(ary1);
    
    // Array ["ant", "bison", "camel", "duck", "elephant"]
    // Array ["camel", "duck", "elephant"]
    // Array ["camel", "duck"]
    // Array ["aaaaa", "bison", "camel", "duck", "elephant"]
    // Array ["camel", "duck", "elephant"]

     

    Array.prototype.sort()

    sort() 메서드는 배열의 요소를 적절한 위치에 정렬한 후 그 배열을 반환합니다. 정렬은 stable sort가 아닐 수 있습니다.
    기본 정렬 순서는 문자열의 유니코드 코드 포인트를 따릅니다.(오름차순)

    stable sort : 졍렬시 같은 값에 대하여 원본 순서가 유지되는 정렬
    unstable sort : 졍렬시 같은 값에 대하여 원본 순서가 유지되지 않는 정렬

     

    Array.prototype.splice()

    splice() 메서드는 배열의 기존 요소를 삭제 또는 교체하거나 새 요소를 추가하여 배열의 내용을 변경합니다.
    만약 제거할 요소의 수와 추가할 요소의 수가 다른 경우 배열의 길이는 달라집니다.

    var months = ['Jan', 'March', 'April', 'June'];
    months.splice(1, 0, 'Feb');
    // inserts at index 1
    console.log(months);
    // expected output: Array ['Jan', 'Feb', 'March', 'April', 'June']
    
    months.splice(4, 1, 'May');
    // replaces 1 element at index 4
    console.log(months);
    // expected output: Array ['Jan', 'Feb', 'March', 'April', 'May']
    
    months.splice(1, 2, 'May');
    console.log(months);
    // expected output: Array ["Jan", "May", "April", "May"]

     

    Array.prototype.toString()

    toString() 메서드는 지정된 배열 및 그 요소를 나타내는 문자열을 반환합니다.

    var array1 = [1, 2, 'a', '1a'];
    
    console.log(array1.toString());
    // expected output: "1,2,a,1a"

     

    Array.prototype.unshift()

    unshift() 메서드는 새로운 요소를 배열의 맨 앞쪽에 추가하고, 새로운 길이를 반환합니다.

    var array1 = [1, 2, 3];
    
    console.log(array1.unshift(4, 5));
    // expected output: 5
    
    console.log(array1);
    // expected output: Array [4, 5, 1, 2, 3]
    
    
    var arr = [1, 2];
    
    arr.unshift(0); // result of call is 3, the new array length
    // arr is [0, 1, 2]
    
    arr.unshift(-2, -1); // = 5
    // arr is [-2, -1, 0, 1, 2]
    
    arr.unshift([-3]);
    // arr is [[-3], -2, -1, 0, 1, 2]
    반응형

    'JavaScript' 카테고리의 다른 글

    ES6_템플릿 리터럴 (Template Literals)  (0) 2022.02.12
    JSDoc을 통해 JavaScript API 문서 만들기  (0) 2020.12.07
    클로져 (Closure)  (0) 2020.10.27
    JavaScript를 위한 자료구조  (3) 2020.10.10
    JavaScript Immutability  (0) 2020.02.29
Designed by Tistory.