[ JS ] 알고리즘에서 자주 활용되는 함수들

이준혁·2024년 2월 1일
0


알고리즘 문제를 풀 때 JavaScript로 자주 사용되는 함수들이 있습니다. 이러한 함수들을 잘 활용하면 코드를 간결하게 작성하고, 효율적으로 문제를 해결할 수 있습니다. 아래에서 몇 가지 유용한 함수들을 살펴봅시다.

1. Array.prototype.sort()

배열의 요소를 정렬하는데 사용됩니다. 기본적으로는 문자열로 변환하여 사전식으로 정렬됩니다. 숫자를 정렬하려면 비교 함수를 제공할 수 있습니다.

const numbers = [4, 2, 8, 5, 1];
numbers.sort((a, b) => a - b);
console.log(numbers); // [1, 2, 4, 5, 8]

2. Array.prototype.map()

배열의 각 요소에 대해 주어진 함수를 호출하고, 그 결과로 새로운 배열을 생성합니다.

const numbers = [1, 2, 3, 4];
const squared = numbers.map(num => num * num);
console.log(squared); // [1, 4, 9, 16]

3. Array.prototype.filter()

주어진 함수의 조건을 만족하는 요소들로 새로운 배열을 생성합니다.

const numbers = [1, 2, 3, 4];
const evenNumbers = numbers.filter(num => num % 2 === 0);
console.log(evenNumbers); // [2, 4]

4. Array.prototype.reduce()

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

const numbers = [1, 2, 3, 4];
const sum = numbers.reduce((acc, num) => acc + num, 0);
console.log(sum); // 10

5. Array.prototype.indexOf() 및 Array.prototype.includes()

indexOf는 배열에서 특정 요소의 인덱스를 찾습니다. 요소가 없으면 -1을 반환합니다. includes는 요소의 존재 여부를 불리언 값으로 반환합니다.

const fruits = ['apple', 'banana', 'orange'];
console.log(fruits.indexOf('banana')); // 1
console.log(fruits.includes('grape')); // false

물론이죠! 아래에는 JavaScript 알고리즘 문제 해결에 도움이 되는 몇 가지 더 많은 함수들과 기술들을 소개하는 블로그 글을 작성해 보았습니다.

6. Array.prototype.forEach()

배열의 각 요소에 대해 주어진 함수를 실행합니다. 주로 반복문을 대체하여 코드를 더 간결하게 만들 수 있습니다.

const numbers = [1, 2, 3, 4];
numbers.forEach(num => console.log(num));
// 1
// 2
// 3
// 4

7. Set 객체

중복을 허용하지 않는 값들의 집합을 나타내는데 사용됩니다. 배열을 Set으로 변환하면 중복된 값이 제거됩니다.

const numbers = [1, 2, 2, 3, 4, 4, 5];
const uniqueNumbers = [...new Set(numbers)];
console.log(uniqueNumbers); // [1, 2, 3, 4, 5]

8. String.prototype.split() 및 Array.prototype.join()

문자열을 배열로 나누거나, 배열을 문자열로 결합하는 데 사용됩니다.

const sentence = "Hello, World!";
const words = sentence.split(' '); // ['Hello,', 'World!']
const newSentence = words.join('-'); // 'Hello,-World!'

9. Math 객체

수학적 연산을 수행하는데 사용됩니다. 예를 들어, Math.max()Math.min()은 배열의 최댓값과 최솟값을 찾는 데 유용합니다.

const numbers = [2, 5, 8, 3, 1];
const maxNumber = Math.max(...numbers); // 8
const minNumber = Math.min(...numbers); // 1

10. 객체 분해 (Object Destructuring)

객체에서 필요한 속성을 추출하여 변수로 할당할 수 있습니다.

const person = { name: 'John', age: 25, city: 'New York' };
const { name, age } = person;
console.log(name, age); // John 25

이러한 함수들을 적절히 활용하여 JavaScript로 작성된 알고리즘 코드를 더 간결하게 만들 수 있습니다. 자주 사용되는 함수들을 익숙하게 사용하면 코드 작성이 더 효율적이고 가독성이 좋아집니다.

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

0개의 댓글

관련 채용 정보