본문 바로가기

JavaScript

[#. JavaScript] Array 배열 함수 모음 Array APIs

반응형

 

 

 

 

자주 쓰는 혹은 자주 쓸 배열 함수들에 대해 정리해 보자

기본적으로 animals라는 배열이 있다고 하자

 

let animals = ["dog", "cat", "bird"];

 

 

 

 

for of

 

반복이 가능한 객체의 모든 원소를 하나씩 추출하여 변수에 담아 반복문을 수행한다

value에는 실제 원소의 값이 담긴다

 

for(let animal of animals) {
  console.log(animal);
}

// "dog"
// "cat"
// "bird"

 

 



forEach()

forEach는 for of와 달리 Array 배열만 반복할 수 있다

 

animals.forEach((animal) => console.log(animal));

// "dog"
// "cat"
// "bird"

 

 



push(), pop()

push는 배열의 에 하나 이상의 요소를 추가하고, 배열의 새로운 길이를 반환한다

pop은 배열에서 마지막 요소를 제거하고 그 요소를 반환한다

 

var count = animals.push("sheep");
console.log(count)	// 4
console.log(animals);	// ["dog", "cat", "bird", "sheep"]

 

console.log(animals.pop());	// "sheep"
console.log(animals);	["dog", "cat", "bird"]

 

 



unshift(), shift()

unshift는 새로운 요소를 배열의 맨 쪽에 추가하고, 새로운 길이를 반환한다

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

push(), pop()에 비해 속도가 느리다

 

var count = animals.unshift("sheep");
console.log(count)	// 4
console.log(animals);	// ["sheep", "dog", "cat", "bird"]

 

console.log(animals.shift());	// "sheep"
console.log(animals);	// ["dog", "cat", "bird"]

 

 

 


splice()

배열의 기존 요소를 삭제 또는 교체하거나 새 요소를 추가하여 배열의 내용을 변경한다

 

console.log(animals.splice(0, 1));	// ["dog"]
console.log(animals);	// ["cat", "bird"]

 



concat()

인자로 주어진 배열이나 값들을 기존 배열에 합쳐서 새 배열을 반환한다

기존 배열을 바뀌지 않는다

 

let color = ["white", "black", "yellow"];
var newArr = animals.concat(color);	
console.log(newArr);	// ["dog", "cat", "bird", "white", "black", "yellow"]

 

 

 


indexOf()
배열에서 지정된 요소를 찾을 수 있는 첫 번째 인덱스를 반환하고, 존재하지 않으면 -1을 반환한다

 

console.log(animals.indexOf("dog"));	// 0
console.log(animals.indexOf("puppy"));	// -1

 

 

 


includes()
배열이 특정 요소를 포함하고 있는지 판별한다

 

console.log(animals.includes("dog"));	// true
console.log(animals.includes("puppy"));	// false

 

 

 

 

join(separator?)
배열의 모든 요소를 연결해 하나의 문자열로 만든다
구분자를 넣으면 구분자를 넣어서 나눠준다

 

console.log(animals.join());	// "dog,cat,bird"
console.log(animals.join("-"))	// "dog-cat-bird"

 

 



split(separator, limit?)
String 객체를 지정한 구분자를 이용하여 여러 개의 문자열로 나누고, 배열에 저장하여 반환한다

 

var str = "The quick brown fox jumps over the lazy dog";
var newStr = str.split(" ");
console.log(newStr);	// ["The", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog"]

 

 



reverse()
배열의 순서를 바꾼다

첫 번째 요소는 마지막 요소가 되며 마지막 요소는 첫 번째 요소가 된다

배열 자체를 수정한다 

 

console.log(animals.reverse());	// ["bird", "cat", "dog"]

 

 

 


slice(start?, end?)

어떤 배열의 start부터 end까지(end 미포함)에 대한 얕은 복사본을 새로운 배열 객체로 반환한다

원본 배열은 바뀌지 않는다

 

console.log(animals.slice(0, 2));	// ["dog", "cat"]
console.log(animals);	// ["dog", "cat", "bird"]

 

 



find(predicate, thisArg?)

주어진 판별 함수를 만족하는 첫 번째 요소의 값 반환한다

그런 요소가 없다면 undefined를 반환한다
찾으면 true가 나오고 해당하는 첫 번째 배열을 return
첫 번째 요소 값'만' 반환

 

let score = [50, 80, 96, 44, 24];
var result = score.find((item) => item < 60);
console.log(result);	// 50
var result2 = score.find((item) => item < 50);
console.log(result2);	// 44
var result3 = score.find((item) => item < 20);
console.log(result3);	// undefined

 

 



filter(value, index?)
주어진 함수(조건)을 만족하는 모든 요소를 모아 새로운 배열로 반환한다

 

var result = score.filter((value) => value == 24);
console.log(result);	// [24]

 

 



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

 

var result = score.map(item => item * 2);
console.log(result);	// [100, 160, 192, 88, 48]

 

 



some()

배열 안의 어떤 요소라도 주어진 판별 함수를 통과하는지 테스트한다
조건에 해당하는 값이 있는지/없는지 true, false를 반환한다

 

var result = animals.some(animal => animal == "dog");
console.log(result);	// true
var result2 = animals.some(animal => animal == "pig");
console.log(result2);	// false

 

 



every()

배열 안의 모든 요소가 주어진 판별 함수를 통과하는지 테스트한다
모든 데이터가 조건에 해당하는지 true, false를 반환한다 

 

var result = score.every(value => value < 80);
console.log(result);	// false

 

 



reduce(prev, curr)
값을 누적할 때 사용한다

배열의 각 요소에 대해 주어진 reducer 함수를 실행하고, 하나의 결과값을 반환한다

 

const arr = [1, 2, 3, 4, 5];
var result = arr.reduce((prev, curr, idx) => { 
  return prev += curr; 
}, 0);
console.log(result);  // 15
var result2 = arr.reduce((prev, curr, idx) => { 
  return prev += curr; 
}, 10);
console.log(result2);  // 25





sort(start?, end?)
배열의 요소를 적절한 위치에 정렬한 후 그 배열을 반환한다

 

console.log(score.sort());	// [24, 44, 50, 80, 96]
var result = score.sort((a, b) => { return b - a });
console.log(result);	// [96, 80, 50, 44, 24]

 

 

 

 

 

 

반응형