Modern Javascipt (배열 내장 함수)

신윤철·2022년 4월 15일
0

JS

목록 보기
3/4
post-thumbnail

이번에는 자주 사용하는 배열 내장 함수를 정리해보겠습니다.

forEach

forEach : 배열을 순회하는 간단한 내장함수

const array = ['a', 'b', 'c', 'd'];

array.forEach((param) => console.log(param)); // a, b, c, d

내장함수 forEach는 push, pop, shift, unshift 등을 함께 사용하여 더 유용하게 사용할 수 있습니다.

const array = ['a', 'b', 'c', 'd'];
const newArray = [];

array.forEach((param) => newArray.push(param + param));

console.log(newArray);  // ['aa', 'bb', 'cc', 'dd']

map

map : 원본 배열을 순환하며 각각 모든 요소마다 콜백함수를 실행하고 return값을 반환

forEach와 비슷하지만 return을 반환하기 때문에 변수에 대입을 할 수 있습니다.

const array = ['a', 'b', 'c', 'd'];

const newArray = array.map((param) => {return param + param + param;})

console.log(newArray); // ['aaa', 'bbb', 'ccc', 'ddd']

includes

includes : 임의의 값이 주어진 배열에 존재하는지 판단 (true, false)

const array = ['a', 'b', 'c', 'd'];
let str = "b";

console.log(array.includes(str));	// true

indexOf

indexOf : 임의의 값이 주어진 배열의 몇번째에 존재하는지 반환. (없으면 -1)

indexOf가 첫번째값 즉, 0을 반환시 False처리가 되는 경우가 있어 (0은 falsy)
이를 보완하기 위해 includes가 등장하였습니다.

const array = ['a', 'b', 'c', 'd'];
let str = "b";

console.log(array.indexOf(str));    // 1

findIndex

findIndex : 조건에 맞는 배열의 인덱스 번호를 반환

const arrObj = [
  {color : "red"},
  {color : "blue"},
  {color : "green"},
  {color : "pink"},
  {color : "blue"}
]

console.log(arrObj.findIndex((value) => { 
  return value.color === "pink";	// 3
}));

find

find : 조건에 맞는 배열의 요소를 반환

const arrObj = [
  {color : "red"},
  {color : "blue"},
  {color : "green"},
  {color : "pink"},
  {color : "blue"}
]

console.log(arrObj.find((value) => {
  return value.color === "pink";	// {color : pink}
}));

filter

filter : 조건에 따라 배열내에서 true를 반환하는 모든 요소 반환

const arrObj = [
  {color : "red"},
  {color : "blue"},
  {color : "green"},
  {color : "pink"},
  {color : "blue"}
]

console.log(arrObj.filter((value) => value.color === "blue"))	// [{color: 'blue'}, {color: 'blue'}]

slice

slice : 조건에 맞게 배열의 요소를 자르는 메서드

const arrObj = [
  {color : "red"},
  {color : "blue"},
  {color : "green"},
  {color : "pink"},
  {color : "blue"}
]

console.log(arrObj.slice(0,3));	[{color: 'red'}, {color: 'blue'}, {color: "green"}]

concat

concat : 두개의 배열을 합치는 메서드

const array = ['a', 'b', 'c', 'd']
const arrObj = [
  {color : "red"},
  {color : "blue"},
  {color : "green"},
  {color : "pink"},
  {color : "blue"}
]

console.log(array.concat(arrObj)); // ['a', 'b', 'c', 'd', {…}, {…}, {…}, {…}, {…}]

sort

sort : 원본 배열의 순서를 사전순으로 정렬

const engs = ['d', 'e', 'a', 'c', 'b'];

engs.sort();

console.log(engs);  //['a', 'b', 'c', 'd', 'e']

하지만 숫자를 정렬할 시 숫자를 문자로 취급하여 1, 12, 2, 233, 3 처럼 정렬합니다.

const numbers = [3,124,23,5,46,345,32,12,3,41,24,2];

numbers.sort();

console.log(numbers); //[12, 124, 2, 23, 24, 3, 3, 32, 345, 41, 46, 5]

// 때문에 비교함수를 만드는 사전 작업이 필요함
const compare = (num1 , num2) => {
  if (num1 > num2){
    // numb1 이 num2 보다 크다면 num1을 num2보다 뒤로 보냄
    return 1;   
  };
  if (num1 < num2){
    // numb1 이 num2 보다 작다면 num1을 num2보다 앞으로 보냄
    return -1;
  };
  return 0;
};
numbers.sort(compare);
console.log(numbers);   //[2, 3, 3, 5, 12, 23, 24, 32, 41, 46, 124, 345]

join

join : 배열의 값을 이어서 출력해주는 메서드

const strings = ["안녕하세요", "자바스크립트", "es6", "이후", "공부중입니다."];

console.log(strings.join(" ")); // 안녕하세요 자바스크립트 es6 이후 공부중입니다.
profile
기본을 탄탄하게🌳

0개의 댓글