Skip to content

Latest commit

 

History

History
437 lines (274 loc) · 9.23 KB

01.Array.md

File metadata and controls

437 lines (274 loc) · 9.23 KB

Array

본 내용은 MDN web docs를 보고 정리한 내용입니다. https://developer.mozilla.org/ko/docs/Web/JavaScript/

MDN web docs를 읽으면서 헷갈리거나 모르고 있었던 Array에 대한 정리.

Array.from()

Array.prototype.concat()

Array.prototype.copyWithin()

Array.prototype.entries()

Array.prototype.fill()

Array.prototype.find()

Array.prototype.flat()

Array.prototype.includes()

Array.prototype.lastIndexOf()

Array.prototype.push()

Array.prototype.shift()

Array.prototype.slice()

Array.prototype.some()

Array.prototype.splice()

Methods

Array.from()

  • return new Array

  • 유사 배열 객체, 반복이 가능한 객체를 얕게 복사하여 새로운 Array를 만든다.

  • Array가 아닌 자료들을 재구성할 때 유용하게 사용될 것 같다.

  • Mapping Func를 활용하면 데이터를 바로 원하는 대로 수정할 수 있다.

  • from() 메서드의 length는 1이다.

    • Array.from({length: 5}).length는 5이다.

Array.from(유사 배열 객체, 맵핑함수, this)

  1. String에서 배열 만들기
Array.from('abc');
=> [ 'a', 'b', 'c']

'abc'.split('');
=> [ 'a', 'b', 'c']
  1. Set에서 배열 만들기

  2. Map에서 배열 만들기

  3. 배열 형태 argument에서 배열 만들기

  4. 화살표 함수와 사용하기

Array.from([1, 2, 3], x => x + x);
=> [ 2, 4, 6 ]
  1. 시퀀스 생성하기

Array.prototype.concat()

  • return New Array

  • 기존 배열을 변경하지 않고 새로운 배열을 반환

array.concat(value1, value2, value3 .....)

parameter를 계속해서 늘릴 수 있다.

const num1 = [1, 2, 3];
const num2 = [4, 5, 6];
const num3 = [7, 8, 9];

num1.concat(num2, num3);
=> [ 1, 2, 3, 4, 5, 6, 7, 8 ,9 ]

참고사항

  • push / pop

    • push는 배열의 길이를 반환한다.
    const num1 = [1, 2, 3];
    const num2 = [4, 5, 6];
    
    const sum = num1.push(num2);
    => 4
    num1
    => [1, 2 ,3, [4, 5, 6]]
    
    • pop은 마지막 요소를 제거하고, 제거한 요소를 반환한다. 즉, 원본을 수정하는 것.
    const num1 = [1, 2, 3];
    const num2 = [4, 5, 6];
    
    num1.push(num2);
    => [1, 2 ,3, [4, 5, 6]]
    num1.pop()
    => [4, 5, 6]
    
  • unshift / shift

    • unshift은 새로운 요소를 맨 앞에 추가하고 길이를 반환한다.

    • shift는 배열에서 첫 번째 요소를 제거하고 요소를 반환한다. 즉, 원본을 수정하는 것

  • splice

    • 요소의 삭제, 교체, 추가등을 할 수 있다.
  • String.prototype.concat

    • String의 concat도 parameter를 계속 늘릴 수 있다.

Array.prototype.copyWithin()

  • return Array

arr.copyWithin(target, start, end);

const test = ['a', 'b', 'c', 'd', 'e'];
test.copyWithin(1, 3, 4); // 'b'를 'd'로 변경.
=> [ 'a', 'd', 'c', 'd', 'e' ]

const test2 = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
test2.copyWithin(0, 3, 7); // d,e,f를 0번째부터 복사
=> [ 'd', 'e', 'f', 'g', 'e', 'f', 'g' ]

Array.prototype.entries()

  • return Array Iterator

arr.entries()

var a = ['a', 'b', 'c'];
var iterator = a.entries();

for (let e of iterator) {
  console.log(e);
}
// [0, 'a']
// [1, 'b']
// [2, 'c']

참고사항

  • Array.prototype.keys() - Array의 key값을 반환한다.

  • Array.prototype.values() - Array의 value를 반환한다.

Array.prototype.every()

  • return Boolean

  • 배열 안에 모든 요소가 조건을 통과할 경우 true를 반환한다.

  • 즉, 전체 요소를 확인하므로 반복문 개념으로 사용되는 듯하다.

  • 조건에 맞지 않는 경우 즉시 false를 반환한다.

  • 배열 전체 내용의 유효성 검사를 진행할 경우 유용하게 사용.

arr.every(callback(currentValue, index, array))

[12, 5, 8, 130, 44].every((elem) => elem >= 10); // false
[12, 54, 18, 130, 44].every((elem) => elem >= 10); // true

참고사항

  • Array.prototype.some() - 배열 안의 어떤 요소라도 조건을 통과하면 true.

Array.prototype.fill()

  • return Array

  • 배열의 start부터 end까지 value로 채운다.

  • 기존 배열의 length를 벗어나지 않는다.

    • 빈 배열을 만들려면 Array(number).fill(Object)를 이용하면 된다.

arr.fill(value, start, end)

[1, 2, 3].fill(4);
=> [ 4, 4, 4 ]

[1, 2, 3].fill(4, 4, 6);
=> [ 1, 2, 3 ] // length를 초과하는 값을 넣어도 기존 배열의 length는 변하지 않는다.

[1, 2, 3].fill(4, 0, 3);
=> [ 4, 4, 4 ]

const preview = [1, 2, 3];
const arr = Array(3).fill({}); // [{}, {}, {}]
preview.concat(Array(3).fill({}));
=> [ 1, 2, 3, {}, {}, {} ]

Array.prototype.find()

  • return Object

  • 조건에 맞는 첫 번째 요소의 값을 반환한다. 없을 경우 undefined를 반환한다.

const test = [{ key: 1 }, { key: 2 }, { key: 3 }, { key: 4 }];

const result = test.find((elem) => elem.key === 4);
=> { key: 4 }

arr.find(callback(element, index, array))

callback의 array는 find를 호출한 자기 자신

참고사항

  • Array.prototype.findIndex() - 찾고자 하는 값의 인덱스를 반환

  • Array.prototype.indexOf() - 찾고자 하는 값이 배열에 존재하는 지 확인할 때 사용 (return Index)

  • Array.prototype.includes() - 찾고자 하는 값이 배열에 존재하는 지 확인할 때 사용 (return Boolean)

Array.prototype.findIndex()

  • 조건에 맞는 첫 번째 인덱스를 반환한다. 없을 경우 -1을 반환한다.
const array1 = [5, 12, 8, 130, 44];
const isLargeNumber = (element) => {
  return element > 5;
};

console.log(array1.findIndex(isLargeNumber));
=> 1 // index 값

Array.prototype.flat()

  • return new Array

  • 모든 하위 배열을 재귀적으로 이어 붙여 새로운 배열을 생성

  • polyfill 없음(2019.09.01 기준)

    • reduce와 concat으로 대체 가능

arr.flat([depth])

depth 값에 따라 몇 번째 depth까지 flat 할지 정할 수 있음.

var arr2 = [1, 2, [3, 4, [5, 6]]];
arr2.flat();
// [1, 2, 3, 4, [5, 6]]

var arr3 = [1, 2, [3, 4, [5, 6]]];
arr3.flat(2);
// [1, 2, 3, 4, 5, 6]
  • reduce와 concat을 이용한 대체
const arr1 = [1, 2, [3, 4]];

//단일 레벨 배열로 평평하게 하려면
const arr2 = arr1.reduce((acc, val) => acc.concat(val), []);// [1, 2, 3, 4]

Array.prototype.includes()

  • return Boolean

  • 특정 요소가 있는지 판별한다.

array.includes(value, index)

여기서 index는 시작지점을 나타낸다.

var pets = ['cat', 'dog', 'bat'];

console.log(pets.includes('cat'));
// expected output: true

console.log(pets.includes('cat', 1));
// expected output: false

console.log(pets.includes('cat', 0));
// expected output: true

console.log(pets.includes('at'));
// expected output: false

Array.prototype.lastIndexOf()

  • return Index

  • 요소가 배열에 존재하는 마지막 인덱스를 반환

array.lastIndexOf(searchValue, fromIndex)

var indices = [];
var array = ['a', 'b', 'a', 'c', 'a', 'd'];
var element = 'a';
var idx = array.lastIndexOf(element);
// idx = 4
while (idx != -1) {
  indices.push(idx);
  idx = idx > 0 ? array.lastIndexOf(element, idx - 1) : -1;
}

Array.prototype.push()

  • return Array's Length

  • 새로운 요소를 추가하고 그 길이를 반환한다.

array.push(element1, element2 .... elementN)

var sports = ['축구', '야구'];
var total = sports.push('미식축구', '수영');

console.log(sports); // ['축구', '야구', '미식축구', '수영']
console.log(total);  // 4

Array.prototype.shift()

  • return Array's Length

  • 맨 앞 요소를 제거하고 제거된 요소를 반환.

var array1 = [1, 2, 3];

var firstElement = array1.shift();

console.log(array1);
// expected output: Array [2, 3]

console.log(firstElement);
// expected output: 1

참고사항

  • push - 배열에 요소를 추가하고 길이를 반환

  • pop - 배열의 마지막 요소를 제거하고 제거된 요소를 반환

  • unshift - 배열의 앞에 요소를 추가하고 길이를 반환

Array.prototype.slice()

  • return new Array

  • 배열의 원하는 범위 만큼 얕은 복사를 진행

var animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];

console.log(animals.slice(2, 4));
// expected output: Array ["camel", "duck"]

참고사항

  • Array.prototype.splice() - 배열의 요소를 추가, 삭제, 수정

Array.prototype.some()

  • return Boolean

  • 하나의 요소라도 조건을 통과하면 true를 반환한다.

  • IE9까지 지원하고 있기에 유용하게 사용할 수 있을듯

array.some(function() {})

var array = [1, 2, 3, 4, 5];

var even = function(element) {
  // checks whether an element is even
  return element % 2 === 0;
};

console.log(array.some(even));
// expected output: true

Array.prototype.splice()

  • return Array

  • 배열의 내용을 추가, 수정, 삭제 가능

  • 제거된 요소들을 반환

array.splice(start, deleteCount, item1, item2 .....)