Array 내장함수

Sujeong K·2022년 8월 15일
0

JavaScript_basic

목록 보기
10/17

forEach

배열의 각 요소들마다 전달하는 함수를 실행

let days = ['mon', 'tue', 'wed'];
days.forEach((x) => console.log(x)); // mon, tue, wed

map

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

const array1 = [1, 4, 9, 16];

// pass a function to map
const map1 = array1.map(x => x * 2);

console.log(map1);
// expected output: Array [2, 8, 18, 32]

📌 map에 전달되는 callback 함수는 호출될 때 대상 요소의 값, 그 요소의 인덱스, 그리고 map을 호출한 원본 배열 3개의 인수를 전달받습니다.


indexOf, includes

배열에 해당 값이 존재하는지 확인

const daysOfWeek = ["mon", "tue", "wed", "thu", "fri", "sat"];
console.log(daysOfWeek.indexOf('tue')); // 1
console.log(daysOfWeek.includes('tue')); // true
console.log(daysOfWeek.indexOf('sun')); // -1
console.log(daysOfWeek.includes('sun')); // false
// indexOf를 사용했을 때 해당 요소가 없으면 -1 출력

indexOf는 인덱스, 혹은 -1 반환
includes는 boolean 반환


findIndex

주어진 판별 함수를 만족하는 첫 번째 요소의 index를 반환. 그런 요소가 없다면 -1을 반환.

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

const isLargeNumber = (element) => element > 13;

console.log(array1.findIndex(isLargeNumber));
// expected output: 3

find

주어진 판별 함수를 만족하는 첫 번째 요소의 값을 반환. 그런 요소가 없다면 undefined를 반환.

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

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

console.log(found);
// expected output: 12
const inventory = [
  {name: 'apples', quantity: 2},
  {name: 'bananas', quantity: 0},
  {name: 'cherries', quantity: 5}
];

function findCherries(x) {
  return x.name === 'cherries';
} 
// 여기서 x는 함수를 실행할 데이터
// x의 속성 중 name의 value가 'cherries'와 같은지 판별 후 boolean 반환

const cherry = inventory.find(findCherries);
console.log(cherry); // {name: 'cherries', quantity: 5}

filter

주어진 함수의 테스트를 통과하는 모든 요소를 모아 새로운 배열로 반환

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

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

console.log(result); // ['exuberant', 'destruction', 'present']

function isBigEnough(value) {
  return value >= 10;
}
const filtered = [12, 5, 8, 130, 44].filter(isBigEnough);
console.log(filtered); // [12, 130, 44]

slice

어떤 배열의 begin부터 end까지(end 미포함)에 대한 얕은 복사본을 새로운 배열 객체로 반환. 원본 배열은 바뀌지 않음.

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

console.log(animals.slice(2));
// expected output: Array ["camel", "duck", "elephant"]
// index 2부터 추출
// end 매개변수 생략시 배열의 끝까지 추출

console.log(animals.slice(2, 4));
// expected output: Array ["camel", "duck"]
// slice 는 end 인덱스를 제외하고 추출합니다.
// index 2인 요소부터 3인 요소까지 추출

console.log(animals.slice(1, 5));
// expected output: Array ["bison", "camel", "duck", "elephant"]
// index 1인 요소부터 4번째 요소까지 추출

console.log(animals.slice(-2));
// expected output: Array ["duck", "elephant"]
// 음수인 start 인덱스는 배열의 끝에서부터의 길이를 나타냅니다. 
// slice(-2) 는 배열에서 마지막 두 개의 엘리먼트를 추출합니다.

console.log(animals.slice(2, -1));
// expected output: Array ["camel", "duck"]
// 음수인 end 인덱스는 배열의 끝에서부터의 길이를 나타냅니다. 
// 예를들어 slice(2,-1) 는 index 2인 요소부터 끝에서 두번째 요소까지 추출합니다.

console.log(animals.slice(2, -2)); // ["camel"]

console.log(animals.slice(2, Infinity)); 
// ["camel", "duck", "elephant"]
// 만약 end 값이 배열의 길이보다 크다면, 배열의 끝까지(arr.length) 추출합니다.

console.log(animals.slice());
// ['ant', 'bison', 'camel', 'duck', 'elephant']
// begin이 undefined인 경우에는, 0번 인덱스부터 slice 합니다.

console.log(animals.slice(5));
// []
// begin이 배열의 길이보다 크면 빈 배열을 반환

concat

배열 합치기

const spring = ["March", "April", "May"];
const summer = ["June", "July", "August"];
const ss = spring.concat(summer); // 새 배열 반환
console.log(ss); // ['March', 'April', 'May', 'June', 'July', 'August']

sort

배열의 요소를 적절한 위치에 정렬한 후 그 배열을 반환.

const items = [
  { name: 'Edward', value: 21 },
  { name: 'Sharpe', value: 37 },
  { name: 'And', value: 45 },
  { name: 'The', value: -12 },
  { name: 'Magnetic', value: 13 },
  { name: 'Zeros', value: 37 }
];

// value 기준으로 정렬
items.sort(function (a, b) {
  if (a.value > b.value) {
    return 1;
  }
  if (a.value < b.value) {
    return -1;
  }
  // a must be equal to b
  return 0;
});

console.log(items.map((item) => item.value));
// [-12, 13, 21, 37, 37, 45]
const array = [45, 80, 90, 66, 88].sort((a, b) => a - b);
console.log(array); // [45, 66, 80, 88, 90]

📌 반환 값은 정렬된 배열. 원 배열이 정렬되는 것에 유의.
compare function 작성해줘야함


join

배열의 모든 요소를 연결해 하나의 문자열로 만듭니다.

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"
  • arr.join([separator])
  • separator : 배열의 각 요소를 구분할 문자열을 지정
  • separator를 생략하면 배열의 요소들이 쉼표(,)로 구분
  • separator는 필요한 경우 문자열로 변환됨
  • separator가 빈 문자열이면 모든 요소들이 사이에 아무 문자도 없이 연결됨

📌배열의 모든 요소들을 연결한 하나의 문자열을 반환. 만약 arr.length 가 0이라면, 빈 문자열을 반환.


더 있는데 추후에 사용하면서 추가할 것..

profile
차근차근 천천히

0개의 댓글