JavaScript 로 알고리즘을 풀 때 유용한 함수 모음✨

혜혜·2023년 1월 17일
0

PS

목록 보기
1/8
post-thumbnail

알고리즘 공부하면서 꾸준히 추가할 예정...👀

✨ 배열 관련 함수

❗ filter()

: 주어진 함수의 테스트를 통과하는 모든 요소를 모아 새로운 배열을 반환
쉽게 말해, 배열에서 특정 조건에 해당하는 요소들만 뽑아서 새 배열 안에 담아 반환해주는 함수!

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"]

❗ 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"

❗ splice()

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

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"]

첫번째 경우는 쉽게 말해, 1번째 index에서 0개의 원소를 삭제하고 'Feb'를 추가하는 것이고,
두번째 경우는 4번째 index에서 1개의 원소를 삭제하고 'May'를 추가하는 것이다.
첫번째 경우처럼 0개의 원소를 삭제하는 경우 그냥 insert 처럼 쓸 수 있는 것.

❗ reduce()

: 배열의 각 요소에 대해 주어진 리듀서(reducer) 함수를 실행하고, 하나의 결과값을 반환

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
  • 리듀서 함수 인자
    ① accumulator : 콜백의 반환값 누적
    ② currentValue : 처리할 현재 요소
    ③ currentIndex : 처리할 현재 요소의 인덱스 (optional)
    ④ array : reduce()를 호출한 배열 (optional)
    ✔ reduce()의 2번째 인자로 initialValue 가 주어지는 경우
  • accumulator == initialValue
  • currentValue == 배열의 첫 번째 값
    ✔ reduce()의 2번째 인자로 initialValue 가 주어지지 않는 경우
  • accumulator == 배열의 첫 번째 값
  • currentValue == 배열의 두 번째 값

❗ includes()

: 배열이 특정 값을 가지고 있는지 여부에 따라 truefalse 를 적절히 반환

const array1 = [1, 2, 3];

console.log(array1.includes(2));
// Expected output: true

const pets = ['cat', 'dog', 'bat'];

console.log(pets.includes('cat'));
// Expected output: true

console.log(pets.includes('at'));
// Expected output: false

1번째 인자 : 배열 안에 들어 있는지 판별하고 싶은 특정 값
2번째 인자(optional) : 어디서부터 확인을 시작할 것인지에 대한 인덱스

❗ from()

: 유사 배열 객체(array-like object)나 반복 가능한 객체를 얕게 복사해, 새로운 Array 객체 생성

console.log(Array.from('foo'));
// Expected output: Array ["f", "o", "o"]

console.log(Array.from([1, 2, 3], x => x + x));
// Expected output: Array [2, 4, 6]

1번째 인자 : 배열로 변환하고자 하는 객체
2번째 인자(optional) : 배열의 모든 요소에 대해 호출할 맵핑 함수
3번째 인자(optional) : 2번째 인자로 들어간 맵핑 함수 실행 시에 this 로 사용할 값

❗ shift()

: 배열에서 첫 번째 요소를 제거하고, 제거된 요소 반환

const array1 = [1, 2, 3];

const firstElement = array1.shift();

console.log(array1);
// Expected output: Array [2, 3]

console.log(firstElement);
// Expected output: 1

✔ 배열이 실제로 변한다는 것 유의

✨ 문자열 관련 함수

❗ split()

: String 객체를 지정한 구분자를 이용하여 여러 개의 문자열로 나눈다.

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."]

❗ match()

: 문자열이 정규식과 매치되는 부분을 검색

var str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
var regexp = /[A-E]/gi;
var matches_array = str.match(regexp);

console.log(matches_array);
// ['A', 'B', 'C', 'D', 'E', 'a', 'b', 'c', 'd', 'e']

❗ replace()

: 어떤 패턴에 일치하는 일부 또는 모든 부분이 교체된 새로운 문자열을 반환

const p = 'The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?';

console.log(p.replace('dog', 'monkey'));
// Expected output: "The quick brown fox jumps over the lazy monkey. If the dog reacted, was it really lazy?"

✨ 객체 관련 함수

❗ keys()

: 주어진 객체의 속성 이름들을 일반적인 반복문과 동일한 순서로 순회되는 열거할 수 있는 배열로 반환
쉽게 말해, Object의 key들을 배열로 반환함

const object1 = {
  a: 'somestring',
  b: 42,
  c: false
};

console.log(Object.keys(object1));
// Expected output: Array ["a", "b", "c"]

❗ values()

: 전달된 파라미터 객체가 가지는 (열거 가능한) 속성의 값들로 이루어진 배열을 반환
쉽게 말해, Object의 value들을 배열로 반환함

const object1 = {
  a: 'somestring',
  b: 42,
  c: false
};

console.log(Object.values(object1));
// Expected output: Array ["somestring", 42, false]
profile
쉽게만살아가면재미없어빙고

0개의 댓글

관련 채용 정보