본문 바로가기
Dev/🟨 JavaScript

[JS] Array Methods를 정리해보아요.

by 아아덕후 2023. 9. 9.
반응형

안녕하세요. 아아덕후입니다.

JavaScript를 사용하면서 느끼는 점은 배열 관련된 메서드가 정말 많다는 것입니다.

예전부터 존재해오던 것 메서드부터 ES5 이후, 그리고 지금도 새로 릴리즈 메서드(ES2023)까지..!

머릿속에 희미하게, 얽혀있는 배열 메서드를 정리하기 위해 이 글을 작성했습니다.

 


목차

  1. slice()
  2. splice()
  3. Concat()
  4. forEach()
  5. indexOf()
  6. lastIndexOf()
  7. includes()
  8. find()
  9. findIndex()
  10.  filter()
  11. reverse()
  12. map()
  13. join()
  14. split()
  15. isArray()
  16. some()
  17. every()
  18. reduce()
  19. sort()
  • 참고 자료

1. slice()

Array.slice(n,m) : n(start) 부터 m(end) 까지 반환한다.

1. n,m이 모두 없으면 배열 전체를 반환(복사)한다.

2. m이 없으면, 배열 끝까지 자른 후 반환한다.

3. m이 음수이면 n**부터** / 뒤에서부터 m번째 까지 자른 후 반환한다.

4. m은 exclusive 하기 때문에 m**번째 요소는 포함하지 않는다**. (m-1 까지만 포함)

function testSlice() {
  let arr = [1, 2, 3, 4, 5];
  const slicedArr0 = arr.slice();
  const slicedArr1 = arr.slice(1);
  const slicedArr2 = arr.slice(1, -1);

  console.log("arr:", arr);
  console.log("slicedArr0:", slicedArr0);
  console.log("slicedArr1:", slicedArr1);
  console.log("slicedArr2:", slicedArr2);
}

testSlice()

// ouput

arr: (5) [1, 2, 3, 4, 5]
slicedArr0: (5) [1, 2, 3, 4, 5]
slicedArr1: (4) [2, 3, 4, 5]
slicedArr2: (3) [2, 3, 4]

배열 자체는 변화없다.

반환 값으로는 삭제된 요소를 반환한다.


2. splice()

Array.splice(n,m, T) : n 부터 m개 지우기

  1. n : start 값 / m(optional) : 지울 개수 / T (optional) : n에 추가할 값
  2. m 이 없을 경우, n부터 끝까지 삭제
  3. T가 있으면(optional) T를 n번째에 추가
  4. T를 여러개 추가 가능
function testSplice() {
  const arr1 = [1, 2, 3, 4, 5];
  const splicedArr1 = arr1.splice(2);

  const arr2 = [1, 2, 3, 4, 5];
  const splicedArr2 = arr2.splice(1, 3, ...[6, 7, 8, 9]);

  const arr3 = [1, 2, 3, 4, 5];
  const splicedArr3 = arr3.splice(1, 3, 6, 7, 8, 9);

  console.log("arr1:", arr1);
  console.log("splicedArr1:", splicedArr1);

  console.log("arr2:", arr2);
  console.log("splicedArr2:", splicedArr2);

  console.log("arr3:", arr3);
  console.log("splicedArr3:", splicedArr3);
}

testSplice();

// output
arr1: (2) [1, 2]
splicedArr1: (3) [3, 4, 5]
arr2: (6) [1, 6, 7, 8, 9, 5]
splicedArr2: (3) [2, 3, 4]
arr3: (6) [1, 6, 7, 8, 9, 5]
splicedArr3: (3) [2, 3, 4]

splicedArr 는 index 1부터 3까지 지우고 ( [1,2,3,4,5] 중 [ 2,3,4 ] 제거 -> [1,5 ]만 남음 )

index 1에 T ( [6,7,8,9] )를 삽입하여 [ 1, 6,7,8,9 ,5 ]가 만들어집니다.

( 이때, spread operator를 사용하지 않으면 배열 자체가 들어가서 [ 1, [6,7,8,9] , 5 ] 가 됩니다.)

splice 메서드는 해당 배열 자체에 적용시키기 때문에 해당 배열 자체가 변합니다.

반환 값으로는 삭제된 요소가 반환됩니다. ( splicedArr)


3. Concat()

Array.concat(a, b, c) : a , b, c ... 인수로 전달된 값들을 배열로 합친다.

  1. arr배열에 a,b,c를 합쳐서 새배열을 반환한다.
  2. a,b,c에 각 요소 / 배열 추가 가능하다.
function testConcat() {
  let arr = [1, 2, 3, 4, 5];
  const concatArr1 = arr.concat([6], [7, 8], [9]);
  const concatArr2 = arr.concat(6, 7, 8, 9);
  // const concatArr = arr.concat(1, 3, 6, 7, 8, 9)
  console.log("arr:", arr);
  console.log("concatArr1:", concatArr1);
  console.log("concatArr2:", concatArr2);
}

testConcat();

// output
arr: (5) [1, 2, 3, 4, 5]
concatArr1: (9) [1, 2, 3, 4, 5, 6, 7, 8, 9]
concatArr2: (9) [1, 2, 3, 4, 5, 6, 7, 8, 9]

배열 자체는 변화가 없다.

반환 값으로 추가된 요소를 반환한다.


4. forEach()

Array.forEach( element , index , arr(해당배열)  ) : 배열을 순회(루프)하며 각 element, index를 반환한다.

  1. arr배열에 3개의 함수를 인수로 사용한다. (보통 첫 번째와 두 번째를 자주 사용한다.)
    1. element: 배열의 해당 요소
    2. index : 인덱스
    3. arr : 해당 배열 자체
function testForEach() {
  let arr = ["Son", "Kane", "Dele"];
  arr.forEach((element, idx, tempArr) => {
    console.log(`element: ${element}`);
    console.log(`idx: ${idx}`);
    console.log(`tempArr: ${tempArr} \n`);
  });
}
testForEach();

// output
element: Son
idx: 0
tempArr: Son,Kane,Dele 

element: Kane
idx: 1
tempArr: Son,Kane,Dele 

element: Dele
idx: 2
tempArr: Son,Kane,Dele

forEach는 배열 루프를 중지하거나 중단할 수 있는 방법이 없다.


5. indexOf()

 Array.indexOf(n,m)  : n을 m의 인덱스부터 찾으며, n의 인덱스 값을 반환한다. ( 없으면 -1 반환 ) 

  1. 첫 번째 인수인 n을 배열 앞에서 부터 찾는다.
  2. 두 번째 인수 m을 입력하면, index = m부터 시작해서 n을 찾는다.
  3. 찾은 값의 index를 반환한다.
function testIndexOf() {
  const arr = [1, 2, 3, 2, 1];
  const result = arr.indexOf(2);
  const result2 = arr.indexOf(1, 3);
  const result3 = arr.indexOf(4, 0);
  console.log("result : ", result);
  console.log("result2 : ", result2);
  console.log("result3 : ", result3);
}
testIndexOf();

// output
result :  1
result2 :  4
result3 :  -1

 


6. lastIndexOf()


 arr.lastIndexOf(n,m) : n을 m의 인덱스부터 뒤에서 찾으며, n의 인덱스 값을 반환한다. ( 없으면 -1 반환 ) 

  1. 첫 번째 인수인 n을 배열 "뒤"에서 부터 찾는다.
  2. 두 번째 인수 m을 입력하면, index = m부터 시작해서 n을 찾는다.
  3. 찾은 값의 index를 반환한다.
function testLastIndexOf() {
  const arr = [1, 2, 3, 2, 1];
  const result = arr.lastIndexOf(1);
  const result2 = arr.lastIndexOf(1, 3);
  const result3 = arr.lastIndexOf(4, 0);
  console.log("result : ", result);
  console.log("result2 : ", result2);
  console.log("result3 : ", result3);
}

testLastIndexOf();

// output
result :  4
result2 :  0
result3 :  -1

7. includes()

Array.includes( X, m ) : X의 값이 배열에 존재하는지 확인한다. ( 존재하면 true , 존재하지 않으면 false 반환 ) 

  1. 배열에 해당 첫 번째 인수 값(x)이 존재하는지 판단하여 Boolean을 반환한다.
  2. m을 넣어주면, index = m 부터 x 값이 존재하는지 판단한다.
function testIncludes() {
  const arr = [1, 2, 3, 2, 1];
  const result = arr.includes(1);
  const result2 = arr.includes(0);
  const result3 = arr.includes(3, 2);
  console.log("result : ", result);
  console.log("result2 : ", result2);
  console.log("result3 : ", result3);
}

testIncludes();

// output
result :  true
result2 :  false
result3 :  true

 

배열에 해당 첫 번째 인수 값(x)이 존재하는지 판단하여 Boolean을 반환한다.
m을 넣어주면, index = m 부터 x 값이 존재하는지 판단한다.

 


8. find()

 arr.find( fn )

  1. 배열을 순회하며 조건이 맞는지 판단하여 true 이면 해당 요소 값을 반환한다.
  2. 조건이 맞는 요소가 여러개라도 첫 번째 true 값만 반환하고 종료된다.
class Company {
  constructor(name, product) {
    this.name = name;
    this.product = product;
  }
}

function testFind() {
  const arr = ["Apple", "Tesla", "MicroSoft", "Google"];
  const arrObj = [
    new Company("Apple", "IPhone"),
    new Company("Tesla", "ModelS"),
    new Company("MicroSoft", "Office"),
    new Company("Google", "YouTube"),
  ];

  const findResult = arr.find((item, idx) => {
    return idx === 2 ? true : false;
  });
  console.log(findResult);

  const findObjResult = arrObj.find((item) => {
    if (item.product === "Office") {
      return true;
    } else return false;
  });
  console.log(findObjResult);
}

testFind();

// output
MicroSoft
Company {name: 'MicroSoft', product: 'Office'}
  • indexOf 처럼 해당 값을 찾는 것이 목적이지만, 복잡한 연산이 가능하도록 인수로 함수를 받을 수 있다.
  • 하지만, 첫 번째 true 값만 반환하고 종료되며 true일 경우의 값을 반환한다.
  • 만약, 해당 값이 존재하지 않으면 undefined를 반환한다.
  • indexOf, includes와 다르게 객체 배열과 같이 복잡한 배열에서 사용할 수 있다.
  • 특정 key - value를 가진 객체를 찾는데 유용하다.

9. findIndex()

Array.findIndex( item, idx, arr ) : 배열을 순회하며 조건이 맞는지 판단하여 true 이면 해당 요소의 index를 반환한다.

 

findIndex 의 파라미터 : item, idx, arr

  1. item : 요소
  2. idx : 인덱스
  3. arr : 해당 배열 자체
// [위 find 코드에서 작성한 클래스를 그대로 사용]

function testFindIndex() {
  const arr = ["Apple", "Tesla", "MicroSoft", "Google"];
  const arrObj = [
    new Company("Apple", "IPhone"),
    new Company("Tesla", "ModelS"),
    new Company("MicroSoft", "Office"),
    new Company("Google", "YouTube"),
  ];

  const findIndexResult = arr.findIndex((item, idx) => {
    return item === "Google" ? true : false;
  });
  console.log(findIndexResult);

  const findIndexObjResult = arrObj.findIndex((item) => {
    if (item.product === "ModelS") {
      return true;
    } else return false;
  });
  console.log(findIndexObjResult);
}
testFindIndex();

// output
3
1
  • indexOf 처럼 해당 값을 찾는 것이 목적이지만 (find와 동일) 복잡한 연산이 가능하도록 인수로 함수를 받을 수 있다.
  • 하지만, 첫 번째 true 값만 반환하고 종료되며 true일 경우의 값을 반환한다.
  • 만약, 해당 값이 존재하지 않으면 undefined를 반환한다.
  • indexOf, includes와 다르게 객체 배열과 같이 복잡한 배열에서 사용할 수 있다.
  • 특정 key - value를 가진 객체의 인덱스를 찾는데 유용하다.

10. filter()

 

Array.filter( item , idx, arr )  :  배열을 순회하며 조건을 만족하는 "모든 요소"를 배열로 반환한다.

 

findIndex 의 파라미터 : item, idx, arr

  1. item : 요소
  2. idx : 인덱스
  3. arr : 해당 배열 자체
// [위 find 코드에서 작성한 클래스를 그대로 사용]

function testFilter() {
  const arr = ["Apple", "Tesla", "MicroSoft", "Google"];
  const arrObj = [
    new Company("Apple", "IPhone"),
    new Company("Tesla", "ModelS"),
    new Company("MicroSoft", "Office"),
    new Company("Google", "YouTube"),
  ];

  const filterResult = arr.filter((item, idx) => {
    return item.includes("l");
  });
  console.log(filterResult);

  const filterObjResult = arrObj.filter((item) => {
    if (item.product.includes("o")) {
      return true;
    } else return false;
  });
  console.log(JSON.stringify(filterObjResult));
  
  // output
  (3) ['Apple', 'Tesla', 'Google']
[{"name":"Apple","product":"IPhone"},{"name":"Tesla","product":"ModelS"},{"name":"Google","product":"YouTube"}]

 

첫 번째 출력 값은 배열을 순회하며 해당 아이템에 문자열 "l" 이 있으면 반환하는 조건을 가진 filter이다.

이로 인해 filterResult 변수에는 문자열 "l"이 포함 된 Apple , Tesla , Google이 배열로 담겼다.

 

두 번째 filter는 객체 배열을 순회하며 해당 객체의 product 프로퍼티의 값이 문자열 "o"를 포함하는 조건을 가진 filter이다.

이를 통해 조건이 true 일 경우 해당 배열을 filterObjResult 변수에 담아 반환한다.

 

정리하면, filter는 배열을 순회하며 특정 조건을 만족하는 요소를 배열 추출한다.


11. reverse()

Array.reverse() :  배열을 역순으로 재정렬하여 반환한다.
기존 배열도 역순으로 재정렬된다.

function testReverse() {
  const arr = ["Apple", "Tesla", "MicroSoft", "Google"];

  const reverseResult = arr.reverse();
  console.log("기존 배열   : ", arr);
  console.log("메서드 배열 : ", reverseResult);
}

testReverse();

// output
기존 배열   :  (4) ['Google', 'MicroSoft', 'Tesla', 'Apple']
메서드 배열 :  (4) ['Google', 'MicroSoft', 'Tesla', 'Apple']

 


12. map() ★★

Array.map(item, idx, array) : 배열 내의 모든 요소에 대하여 주어진 함수를 호출한 결과를 모아 새로운 배열을 반환한다.

 

function testMap() {
  const arrObj = [
    new Company("Apple", "IPhone"),
    new Company("Tesla", "ModelS"),
    new Company("MicroSoft", "Office"),
    new Company("Google", "YouTube"),
  ];

  const mapResult = arrObj.map((item, index) => {
    const { name, product } = item;
    return {
      id: index,
      name,
      product: `${product} Plus`,
    };
  });
  console.log(JSON.stringify(arrObj));
  console.log(JSON.stringify(mapResult));
}
testMap();

// output
[
	{"name":"Apple","product":"IPhone"},
	{"name":"Tesla","product":"ModelS"},
    {"name":"MicroSoft","product":"Office"},
    {"name":"Google","product":"YouTube"}
]

[
	{"id":0,"name":"Apple","product":"IPhone Plus"},
	{"id":1,"name":"Tesla","product":"ModelS Plus"},
 	{"id":2,"name":"MicroSoft","product":"Office Plus"},
 	{"id":3,"name":"Google","product":"YouTube Plus"}     
]

배열을 순회하며 각 요소(item)에 함수(fn) 실행 결과 값으로 새로운 배열을 만들어 반환한다. 

기존 배열은 그대로 유지한다.


13. join()

Array.join( x ) : 파라미터 x에 구분자 로 전달하면, 해당 구분자를 기준으로 배열을 연결하여 문자열로 반환한다.

function testJoin() {
  const arr = ["Apple", "IPhone 15", "Comming", "Soon", "!"];

  const joinResult = arr.join();
  console.log(joinResult);

  const joinResult2 = arr.join("_");
  console.log(joinResult2);
  const joinResult3 = arr.join(" ");
  console.log(joinResult3);
}

testJoin();

//output
Apple,IPhone 15,Comming,Soon,!
Apple_IPhone 15_Comming_Soon_!
Apple IPhone 15 Comming Soon !

구분자를 전달하지 않으면, 쉼표로 구분되어 연결된다.
기존 배열은 그대로 유지한다.


14. split()

Array.split(x, limit) : 구분자를 첫 번째 파라미터(x)로 전달하면, 해당 구분자 기준으로 문자열을 분리하여 배열로 반환한다.
해당 구분자는 삭제한다.

두번째 파라미터인 limit에 숫자를 전달하면, 해당 숫자의 길이 까지만 배열로 반환한다.

function testSplit() {
  const joinedStr = "Apple,IPhone 15,Comming,Soon,!";
  const splitResult = joinedStr.split(",");
  console.log(splitResult);

  const splitResult2 = joinedStr.split("");
  console.log(splitResult2);
}
testSplit();

// output
['Apple', 'IPhone 15', 'Comming', 'Soon', '!']
['A', 'p', 'p', 'l', 'e', ',', 'I', 'P', 'h', 'o', 'n', 'e', ' ', '1', '5', ',', 'C', 'o', 'm', 'm', 'i', 'n', 'g', ',', 'S', 'o', 'o', 'n', ',', '!']

구분자를 전달하지 않으면, 모든 문자열을 한 글자씩 분리하여 배열로 반환한다.
기존 배열은 그대로 유지한다.


15. isArray()

Array.isArray( x ) : x가 배열이면 true, 아니면 false를 반환한다.

function testIsArray() {
  const obj = {
    company: "SamSung",
    product: "Galaxy S24",
  };

  const arr = ["Apple", "IPhone 15", "Comming", "Soon", "!"];

  const resultIsArray2 = Array.isArray(obj);
  // console.log("obj isArray ? :", resultIsArray2);

  const resultIsArray = Array.isArray(arr);
  // console.log("arr isArray ? :", resultIsArray);

  console.log("obj type : ", typeof obj, "// obj isArray ? :", resultIsArray2);
  console.log("arr type : ", typeof arr, "// arr isArray ? :", resultIsArray);
}
testIsArray();

// output
obj type :  object // obj isArray ? : false
arr type :  object // arr isArray ? : true

 typeOf로 해당 변수의 타입을 확인할 때, 배열도 Object로 반환한다.
 따라서 배열인지 아닌지 확인할 때는 Array.isArray()를 사용해야한다.


16. some()


 Array.some( fn )
배열을 순회하며 함수를 만족하는 요소가 있으면 "순회를 멈추고" true를 반환한다.
만족하는 요소가 없으면 false를 반환한다.

function testSome() {
  const arr = ["Apple", "IPhone 15", "Comming", "Soon", "!"];

  const resultSome = arr.some((str1) => {
    console.log(str1);
    return str1 === "Commin2g";
  });
  console.log(resultSome);
}

testSome();

// output
Apple
IPhone 15
Comming
Soon
!
false

forEach는 중간에 멈춤이 불가능하지만, some을 이용하면 순회를 하며 특정 조건에서 true를 반환하여 멈출 수 있다.

 


17. every()

 Array.every( fn )
배열을 순회하며 모든 요소함수를 만족 하면 true를 반환한다.
만족하는 요소가 하나라도 없으면 false를 반환하며 순회를 멈춘다.

function testEvery() {
  const arr = ["Appolo", "IPhone 15", "Comming", "Soon", "o!"];

  const resultEvery = arr.every((arrItem) => {
    console.log(arrItem);
    return arrItem.includes("o");
  });
  console.log(resultEvery);

  const resultEvery2 = arr.every((arrItem) => {
    console.log(arrItem);
    return arrItem.includes("e");
  });
  console.log(resultEvery2);
}

testEvery();

// output
Appolo
IPhone 15
Comming
Soon
o!
true
Appolo
false

해당 배열내에 모든 값을 검증할 때 사용한다.


18. reduce()

  1. 배열을 순회하며 함수를 실행한다.
  2. 콜백함수의 인수는 4개로, (acc, cur, idx, arr) 이다.
    1. acc : 누적값
    2. cur : 현재 값 (요소)
    3. idx : 인덱스
    4. arr : 해당 배열 자체
  3. 함수의 반환값(retuern으로 지정해주어야함)은 acc에 누적되며, 최종적으로 반환된다.
  4. reduce의 두 번째 파라미터(initialValue) 로 초기값을 전달할 수 있다.
  5. 초기값을 전달하지 않으면, 배열의 첫 번째 요소가 초기값이 된다.
  6. reduce는 순회를 멈추지 않고 모든 요소를 순회한다.
class Student {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
  getName() {
    return this.name;
  }
  getAge() {
    return this.age;
  }
}

function testReduce() {
  const strArr = ["a", "b", "c", "d", "e"];

  const resultStrReduce = strArr.reduce((prev, cur, idx) => {
    return prev + cur + "_";
  }, "");
  // console.log(resultStrReduce);

  const students = [
    new Student("Son", 29),
    new Student("Hwang", 27),
    new Student("Kane", 26),
    new Student("Kdb", 21),
    new Student("Holand", 20),
  ];

  const resultReduce = students.reduce((acc, cur, idx, arr) => {
    console.log(acc, cur, cur.age, idx);
    return acc + cur.age;
  }, 0);
  console.log("resultReduce: ", resultReduce);

  const resultReduce2 = students.reduce((acc, cur) => acc + cur.age, 0);
  console.log("resultReduce2 : ", resultReduce2);

  const resultReduce3 = students.reduce((acc, cur) => {
    if (cur.age >= 25) {
      acc.push(cur.name);
    }
    return acc;
  }, []);
  console.log(resultReduce3);
}
testReduce();


// output
0 Student {name: 'Son', age: 29} 29 0
29 Student {name: 'Hwang', age: 27} 27 1
56 Student {name: 'Kane', age: 26} 26 2
82 Student {name: 'Kdb', age: 21} 21 3
103 Student {name: 'Holand', age: 20} 20 4
resultReduce:  123
resultReduce2 :  123
(3) ['Son', 'Hwang', 'Kane']

 


19. sort()

 Array.sort( fn )

  1. 배열을 순회하며 콜백함수를 실행한다.
  2. 콜백함수의 인수는 2개로, (a, b) 이다.
    1. a : 현재 값 (요소)
    2. b : 다음 값 (요소)
  3. 콜백함수에 인수를 넣어주지 않으면 문자열 순으로 정렬된다.
  4. 콜백함수 반환 값이 a-b 이면, b를 a보다 낮은 인덱스(오름차순)로 정렬한다. (ascending)
  5. 콜백함수 반환 값이 b-a 이면, a를 b보다 낮은 인덱스(내림차순)로 정렬한다. (descending)
  6. sort의 반환값은 정렬된 배열이다.
  7. sort는 순회를 멈추지 않고 모든 요소를 순회한다.
  8. 배열 자체를 변경한다.
function testSort() {
  const studentAges = [12, 562, 14, 7, 55, 95];
  const resultSort = [...studentAges].sort();
  const resultSort2 = [...studentAges].sort((a, b) => {
    return a - b;
  });
  const resultSort3 = [...studentAges].sort((a, b) => {
    return b - a;
  });
  console.log(studentAges);
  console.log(resultSort);
  console.log(resultSort2);
  console.log(resultSort3);
}
testSort();

// output
(6) [12, 562, 14, 7, 55, 95]
(6) [12, 14, 55, 562, 7, 95]
(6) [7, 12, 14, 55, 95, 562]
(6) [562, 95, 55, 14, 12, 7]

 


참고

- MDN : https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array 

- [YouTube] : https://youtu.be/pJzO6O-aWew?si=-xCLSRifFOZXT0z7 

- [ YouTube ] : https://youtu.be/RW25tEAMC9w?si=-lUKpris2IAtAlYn 

- [ YouTube ] : https://www.youtube.com/watch?v=3CUjtKJ7PJg 

반응형

댓글