[DAY13] 자주 쓰이는/헷갈리는 array 메서드(+string 메서드도 쩎꿈 추가)

1nxeo·2023년 2월 18일

항해99

목록 보기
13/63
post-thumbnail

1. arr.reduce( )

console.log( [1,2,3,4].reduce((accumulator, currentValue, index, array) => accumulator + currentValue, 0));

#accumulator : 구문의 끝부분에 있는 숫자 0의 값을 인자로 받는다. 해당 숫자는 누산기의 초기값을 설정한다. 숫자가 바뀌면 초기값이 변경된다.
#currentValue : reduce메서드를 통해서 배열에서 순차적으로 가져올 인자로, 1,2,3,4가 순차적으로 입력된다.
#index : 고유한 위치값으로 새로운 인덱스를 부여한다.
#array : reduce메서드의 this에 해당되는 배열 전체를 불러온다.

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

// 0 + 1 + 2 + 3 + 4
const initialValue = 0;
const sumWithInitial = array1.reduce(
  (accumulator, currentValue) => accumulator + currentValue,
  initialValue
);

console.log(sumWithInitial);
// Expected output: 10

2. arr.fill( )

arr.fill("*", #시작위치, #종료위치)

해당 메서드는 원본 배열을 입력된 내용을 전부 채워넣는 것
변경에 대한 언급 없이, 내용만 입력한 경우 배열 전체를 바꾼다

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

// Fill with 0 from position 2 until position 4
console.log(array1.fill(0, 2, 4));
// Expected output: Array [1, 2, 0, 0]

// Fill with 5 from position 1
console.log(array1.fill(5, 1));
// Expected output: Array [1, 5, 5, 5]

console.log(array1.fill(6));
// Expected output: Array [6, 6, 6, 6]

3. arr.splice( )

arr.splice(#1, #2, #3, #4, #5 ...)

// #1 : 변경을 시작할 고유한 위치값을 지정한다.
// #2 : 변경을 종료할 고유한 위치값을 지정한다.
// #3 이후 : 변경을 시작할 고유한 위치값으로부터 추가할 내용이 기록된다.
const months = ['Jan', 'March', 'April', 'June'];
months.splice(1, 0, 'Feb');
// Inserts at index 1
console.log(months);
// Expected output: Array ["Jan", "Feb", "March", "April", "June"]

months.splice(4, 1, 'May');
// Replaces 1 element at index 4
console.log(months);
// Expected output: Array ["Jan", "Feb", "March", "April", "May"]

4. arr.slice( )

arr.slice(#1, #2)

// #1 : 배열에서 내용을 가져올 시작점의 고유한 위치값
// #2 : 배열에서 내용을 가져올 종료점의 고유한 위치값
const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];

console.log(animals.slice(2));
// Expected output: Array ["camel", "duck", "elephant"]

console.log(animals.slice(2, 4));
// Expected output: Array ["camel", "duck"]

console.log(animals.slice(1, 5));
// Expected output: Array ["bison", "camel", "duck", "elephant"]

console.log(animals.slice(-2));
// Expected output: Array ["duck", "elephant"]

console.log(animals.slice(2, -1));
// Expected output: Array ["camel", "duck"]

console.log(animals.slice());
// Expected output: Array ["ant", "bison", "camel", "duck", "elephant"]

원본배열의 특정한 위치에 있는 값을 복사
음수 -1, -2가 입력되면, 배열의 마지막 요소부터 음수로 지정된 값만큼을 복사

5. arr.filter( )

arr.filter((element, index, arr) => arr.indexOf(element) === index)

자신을 호출한 배열의 "모든 요소"를 살펴보며, 검색기능을 수행

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

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

console.log(result);
// Expected output: Array ["exuberant", "destruction", "present"]

find : 하나를 발견하면 메서드의 실행을 종료

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

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

console.log(found);
// Expected output: 12

6. arr.join( )

join 메서드는 원본 배열의 모든 요소를 문자열로 변환한 후, 이를 연결한 문자열을 반환

const str = 'The quick brown fox jumps over the lazy dog.';

const words = str.split(' ');
console.log(words[3]);
// Expected output: "fox"

const chars = str.split('');
console.log(chars[8]);
// Expected output: "k"

const strCopy = str.split();
console.log(strCopy);
// Expected output: Array ["The quick brown fox jumps over the lazy dog."]

7. str.split( )

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"

8.arr.indexOf( )

const beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];

console.log(beasts.indexOf('bison'));
// Expected output: 1

// Start from index 2
console.log(beasts.indexOf('bison', 2));
// Expected output: 4

console.log(beasts.indexOf('giraffe'));
// Expected output: -1
profile
항상 피곤한 인서의 개발블로그

0개의 댓글