array 메서드 정리

김정민·2021년 12월 7일
0
post-thumbnail

pop()

pop() 메서드는 배열에서 마지막 요소를 제거하고 그 요소를 반환합니다.

arr.pop()

let 과일 = ['사과','수박','복숭아'];

let 꺼낸과일 = 과일.pop();

과일 //['사과','수박']
꺼낸과일 //'복숭아'

배열자체를 바꾼다!! and 배열에서 제거한 요소도 반환한다

꺼내는 용도 , 담는용도 둘 다 사용

push()

push() 메서드는 배열의 끝에 하나 이상의 요소를 추가하고, 배열의 새로운 길이를 반환합니다.

arr.push(element1[, ...[, elementN]])

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

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

배열자체를 바꾼다!!
반환값은 추가한 배열의 새 길이 값을 포함한다

unshift()

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

arr.unshift([...elementN])

const array1 = [1, 2, 3];

console.log(array1.unshift(4, 5));
// expected output: 5

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

배열자체를 바꾼다!!\
반환값은 추가한 배열의 새 길이 값을 포함한다

shift()

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

arr.shift()

const array1 = [1, 2, 3];

const firstElement = array1.shift();

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

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

**배열자체를 바꾼다!!**\
**반환**값은 배열에서 제거한 요소. 빈 배열의 경우 undefined 를 반환합니다

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

```js
const array1 = [1, 2, 'a', '1a'];

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

let arrTosrt = array1.toString()
arrTosrt//"1,2,a,1a"

배열자체에 영향을 주진 않는다
반환값은 배열을 표현하는 문자열을 반환합니다.

join()

join() 메서드는 배열의 모든 요소를 연결해 하나의문자열로 만듭니다.

arr.join([separator])

const elements = ['Fire', 'Air', 'Water'];

console.log(elements.join());
// expected output: "Fire,Air,Water"

console.log(elements.join(''));
// expected output: "FireAirWater"

console.log(elements.join('-'));
// expected output: "Fire-Air-Water"

elements // ['Fire', 'Air', 'Water'];

let elementsJoin = elements.join('-')
elementsJoin "Fire-Air-Water"


**배열자체를 영향을 주진 않는다**
**반환**값은 배열의 모든 요소들을 연결한 하나의 문자열을 반환합니다. 만약 arr.length 가 0이라면, 빈 문자열을 반환합니다.

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

```js
const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];

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

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

console.log(animals.slice(1, 5));
// expected output: Array ["bison", "camel", "duck", "elephant"]

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

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

animals // ['ant', 'bison', 'camel', 'duck', 'elephant'];

const animalsSlice = animals.slice(2, -1)
animalsSlice //["camel", "duck"]

원본 배열자체에영향을 주진 않는다
반환값은 추출한 요소를 포함한 새로운 배열.

splice()

splice() 메서드는 배열의 기존 요소를 삭제 또는 교체하거나 새 요소를 추가하여 배열의 내용을 변경합니다.

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

const 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"]

deleteCount Optional

배열에서 제거할 요소의 수입니다.
deleteCount를 생략하거나 값이 array.length - start보다 크면 start부터의 모든 요소를 제거합니다.
deleteCount가 0 이하라면 어떤 요소도 제거하지 않습니다. 이 때는 최소한 하나의 새로운 요소를 지정해야 합니다

item1, item2, ... Optional

배열에 추가할 요소입니다. 아무 요소도 지정하지 않으면 splice()는 요소를 제거하기만 합 니다.

원본 배열자체를 바꾼다!!
반환값은 제거한 요소를 담은 배열. 하나의 요소만 제거한 경우 길이가 1인 배열을 반환합니다. 아무 값도 제거하지 않았으면 빈 배열을 반환합니다.

concat()

concat() 메서드는 인자로 주어진 배열이나 값들을 기존 배열에 합쳐서 새 배열을 반환합니다.

array.concat([value1[, value2[, ...[, valueN]]]])

const array1 = ['a', 'b', 'c'];
const array2 = ['d', 'e', 'f'];
const array3 = array1.concat(array2);

console.log(array3);
// expected output: Array ["a", "b", "c", "d", "e", "f"]

여러개 이어붙이기도 가능
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]


**원본 배열자체에 영향을 주진 않는다**
**반환**값은 기존 배열에 합쳐서 새 배열을 반환합니다.


## reverse()
reverse() 메서드는 배열의 순서를 반전합니다. 첫 번째 요소는 마지막 요소가 되며 마지막 요소는 첫 번째 요소가 됩니다

```js
const array1 = ['one', 'two', 'three'];

const reversed = array1.reverse();
console.log('reversed:', reversed);
// expected output: "reversed:" Array ["three", "two", "one"]

// Careful: reverse is destructive -- it changes the original array.
console.log('array1:', array1);
// expected output: "array1:" Array ["three", "two", "one"]

원본 배열자체를 바꾼다!!
반환값은 순서가 반전된 새배열. (원본도 바꾸고 반환값도 있는)

sort()

sort() 메서드는 배열의 요소를 적절한 위치에 정렬한 후 그 배열을 반환합니다. 정렬은 stable sort가 아닐 수 있습니다. 기본 정렬 순서는 문자열의 유니코드 코드 포인트를 따릅니다.
정렬 속도와 복잡도는 각 구현방식에 따라 다를 수 있습니다.

arr.sort([compareFunction])

const months = ['March', 'Jan', 'Feb', 'Dec'];
months.sort();
console.log(months);
// expected output: Array ["Dec", "Feb", "Jan", "March"]

const array1 = [1, 30, 4, 21, 100000];
array1.sort();
console.log(array1);
// expected output: Array [1, 100000, 21, 30, 4]
사전식 정렬이라 원하는대로 안되는 것이다

compareFunction Optional

정렬 순서를 정의하는 함수. 생략하면 배열은 각 요소의 문자열 변환에 따라 각 문자의 유니 코드 코드 포인트 값에 따라 정렬됩니다.

안에 콜백함수를 넣어서 정렬 기준을 바꿀 수 있어요

data.sort((a, b) => a - b) // 오름차순
data.sort((a, b) => b - a) // 내림차순

원본 배열자체를 바꾼다!!
반환값은 순서가 반전된 새배열. (원본도 바꾸고 반환값도 있는)

keys()

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

arr.keys()

const array1 = ['a', 'b', 'c'];
const iterator = array1.keys();

for (const key of iterator) {
console.log(key);
}

// expected output: 0
// expected output: 1
// expected output: 2

**원본 배열자체에 영향을 주진 않는다**
**반환**값은 새로운 Array 반복기 객체.

## values()
values() 메서드는 배열의 각 인덱스에 대한 값을 가지는 새로운 Array Iterator 객체를 반환합니다.
> arr.values()

```js
const array1 = ['a', 'b', 'c'];
const iterator = array1.values();

for (const value of iterator) {
  console.log(value);
}

// expected output: "a"
// expected output: "b"
// expected output: "c"

원본 배열자체에 영향을 주진 않는다
반환값은 새로운 Array 반복기 객체.

map()

map() 메서드는 배열 내의 모든 요소 각각에 대하여 주어진 함수를 호출한 결과를 모아 새로운 배열을 반환합니다.

arr.map(callback(currentValue[, index[, array]])[, thisArg])

const numbers = [1]; 
numbers.map((number, index, source) => { 
  // number: 요소값 
  // index: source에서 요소의 index 
  // source: 순회하는 대상 
  console.log(number); // 1 
  console.log(index); // 0 
  console.log(source); // [1] 
  return number * number; 
});
보통 number 요소값만 넣어서 사용하긴한다

원본 배열자체에 영향을 주진 않는다
반환값은 배열의 각 요소에 대해 실행한 callback의 결과를 모은 새로운 배열.

map과 forEach의 차이점

  1. 새로운 배열을 반환하는 map()

다른 점을 알아보자.

forEach()가 배열 요소마다 한 번씩 주어진 함수(콜백)를 실행하는 것과 달리,

map()은 배열 내의 모든 요소 각각에 대하여 주어진 함수(콜백)를 호출한 결과를 모아 새로운 배열을 반환한다는 특징을 가지고 있다.

// Example of forEach()

const arr = [1, 2, 3, 4, 5];
const mulArr = [];

arr.forEach(num => {
  mulArr.push(num * 3);
});

console.log(mulArr); // [3, 6, 9, 12, 15]


// Example of map()

const arr = [1, 2, 3, 4, 5];
const mulArr = arr.map(num => num * 3);

console.log(mulArr); // [3, 6, 9, 12, 15]
  1. 리턴값을 보내지 않는 forEach()

forEach()는 문밖으로 리턴값을 받지 못한다. 아래의 코드를 살펴보자.

let arr = [1,2,3,4,5];
let a = arr.forEach(function(value){
	return value;
});
console.log(a);   //undefined

이렇게 undefined가 출력된다.

하지만 같은 경우라도 map을 이용하면 다르다.

let arr=[1,2,3,4,5];
let a = arr.map(function(value){
	return value +1;
});
console.log(a);  // [2,3,4,5,6]

즉, forEach와 map의 가장 큰 차이는 바로 리턴값에 있다.

성능면에서는 map이 forEach보다 빠르고 유리하다.

상황에 따라 맞게 사용하면 될 것이다

map 보기쉬운 예제 사진

filter()

filter() 메서드는 주어진 함수의 테스트를 통과하는 모든 요소를 모아 새로운 배열로 반환합니다.

arr.filter(callback(element[, index[, array]])[, thisArg])

const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];

const result = words.filter(word => word.length > 6);

console.log(result);
// expected output: Array ["exuberant", "destruction", "present"]



//콜백을 이용해서 사용하는 법
function isBigEnough(value) {
  return value >= 10;
}

var filtered = [12, 5, 8, 130, 44].filter(isBigEnough);
// filtered 는 [12, 130, 44]

조건에서 true인 것만 가져와서 새로운 배열을 만든다

원본 배열자체에 영향을 주진 않는다
반환값은 테스트를 통과한 요소로 이루어진 새로운 배열. 어떤 요소도 테스트를 통과하지 못했으면 빈 배열을 반환합니다.

삼항연사자와 응용해서 사용하는 이미지

filter와 비슷한 find

find는 찾으면 멈춘다 ((아이디는 중복될일이 없다..))

filter는 다 찾을 것 이야

find()

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

arr.find(callback[, thisArg])

const array1 = [5, 12, 8, 130, 44];

const found = array1.find(element => element > 10);

console.log(found);
// expected output: 12

원본 배열자체에 영향을 주진 않는다
반환값은 주어진 판별 함수를 만족하는 첫 번째 요소의 값. 그 외에는 undefined.

reduce()

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

arr.reduce(callback[, initialValue])

const array1 = [1, 2, 3, 4];
const reducer = (previousValue, currentValue) => previousValue + currentValue;

// 1 + 2 + 3 + 4
console.log(array1.reduce(reducer));
// expected output: 10

// 5 + 1 + 2 + 3 + 4
console.log(array1.reduce(reducer, 5));
// expected output: 15

리듀서 함수는 네 개의 인자를 가집니다.
reduce의 인자로는 총4개를 받을수가 있는데 이전값,현재값,index,배열을 받을수가 있다.

  1. 누산기 (acc)
  2. 현재 값 (cur)
  3. 현재 인덱스 (idx)
  4. 원본 배열 (src)
    리듀서 함수의 반환 값은 누산기에 할당되고, 누산기는 순회 중 유지되므로 결국 최종 결과는 하나의 값이 됩니다.

이전에 살펴본 map과 달리 reduce는 배열이 아닌 하나의 값으로 출력을 하고 있다.

이전값과 현재값을 더하는 방식으로 값을 출력해 내는데

원본 배열자체에 영향을 주진 않는다
반환값은 누적 계산의 결과 값.

요즘은 잘안쓰인다

filter , map ~~등등 체인닝해서 엄청 사용한다..!! (중요)

map중첩해서 쓰거나

그 외 메서드 flat() includes()

0개의 댓글

관련 채용 정보