자바스크립트에서 배열과 객체를 다룰 때 유용한 문법과 함수정리-2

2020. 4. 16. 17:16TypeScript&JavaScript/JavaScript

Map은 배열 안의 원소를 변환하고 싶을 때 사용

indexOf는 객체가 아닌 원소의 위치를 찾는데 사용

findIndex는 객체나 조건에 따른 인덱스를 찾을 때 사용

find는 해당 조건과 일치하는 객체를 반환할 때 사용

filter는 특정 조건의 원소들을 찾아 새 배열을 생성

splice는 특정 원소를 제거할 때 사용. 인자로 인덱스가 필요하다. 제거된 원소를 반환한다

slice는 특정 인덱스부터 인덱스까지 원소를 자를 때 사용, 원래의 배열에는 영향을 끼치지 않는다. 자른 범위의 원소를 반환한다.

shift 배열에서 맨 앞부터 순서대로 특정 요소를 뺀다 

unshift 배열의 맨 앞부분에 원소를 추가한다

pop은 배열 맨 뒤에서 부터 순서대로 특정 요소를 뺀다.

push는 배열 맨 뒤에 특정 원소를 추가한다

concat 은 배열을 합쳐서 반환한다. 기존 배열에 영향을 끼치지는 않는다.

join 은 인자를 단위로 배열을 문자열로 만들어준다

reduce 는 배열의 원소들을 누적된 합, 평균 등을 구하거나 하는데에 쓰면 편리하다. 두 번째 인자는 accumulator의 기본값이다. reduce는 내부에서 콜백을 반환하며 그 반환값이 다음 루프 인덱스의 accumulator가 되고, current가 현재 인덱스의 원소 값이 된다. 이를 잘 활용하면 유용하게 사용할 수 있다.

const array = [1, 2, 3, 4, 5, 6, 7, 8];

const squared = [];
array.forEach(n => {
	squared.push(n * n);
});

// map 사용시 배열의 원소를 변경하는 방식

const square = n => n * n;
const squared = array.map(square);

// const squared = array.map(n => n * n);

const items = [
	{
    	id: 1,
        text: 'hello'
    },
    {
    	id: 2,
        text: 'bye'
    }
];

const texts = items.map(item => item.text);
console.log(texts); // ["hello", "bye"]

//배열의 원소 위치를 찾는 indexOf함수

const superheroes = ['아이언맨', '캡틴 아메리카', '토르', '닥터 스트레인지'];
const index = superheroes.indexOf('닥터 스트레인지');
console.log(index); // 3

//배열의 원소가 객체이거나 조건에 따라 찾아야 할 경우

const todos = [
	{
    	id: 1,
        text: '자바스크립트 입문',
        done: true,
    },
    {
    	id: 2,
        text: '함수 배우기',
        done: true,
    },
    {
    	id: 3,
        text: '객체와 배열 배우기',
        done: true,
    },
    {
    	id: 4,
        text: '배열 내장함수 배우기',
        done: false
    }
]

//const index = todos.indexOf(3);
//console.log(index); -1 : false, 맞는 조건이 없다는 뜻, 객체에는 indexOf를 사용할 수 없다

const index = todos.findIndex(todo => todo.id === 3);
console.log(index); // 2, 인덱스를 정상적으로 찾았다.

const todo = todos.find(todo => todo.id === 3);
console.log(todo);  // 일치하는 객체를 반환


//slice, splice

const numbers = [10, 20, 30, 40];
const idx = numbers.indexOf(30);

console.log(idx); // 2

const spliced = numbers.splice(idx, 1);
console.log(numbers); //[10,20,40]
console.log(spliced); // 30

conse sliced = numbers.slice(0, 2);
console.log(sliced); // [10, 20]
console.log(numbers); // [10,20,30,40] : 기존의 배열에 영향이 없음

//concat

const arr1 = [1,2,3];
const arr2 = [4,5,6];

const concated = arr1.concat(arr2);
console.log(concated); // [1,2,3,4,5,6]


//join

const arr3 = [1,2,3,4];

const join = arr3.join(', '); 
console.log(join); // 1, 2, 3, 4


//reduce

const reduceNumbers = [1,2,3,4,5];

const avg = numbers.reduce((accumulator, current, index, array) => {
	if(index === array.length - 1) {
    	return (accumulator + current) / array.length;
    }
    return accumulator + current;
}, 0);

console.log(avg) // 3

//reduce 다른 예시

const alphabets = ['a', 'a', 'a', 'b', 'c', 'c', 'd', 'e'];
const counts = alphabets.reduce((acc, current) =>  {
                  if (acc[current]) {
                      acc[current] += 1;   
                  } else {
                      acc[current] = 1;
                  }
                  return acc;
              }, {})

console.log(counts); // {a:3, b:1, c:2, d:1, e:1}