728x90

✨ 내가 제공한 function통과(pass)하는 값(element)들을 새로운 배열로 만들어주는 helper method

💻Example Code

ex1)
const originArr = [ 1, 2, 3, 4, 5 ];
const passedArr = originArr.filter( num => num !== 3 );

console.log(originArr);
console.log(passedArr);

실행 결과(3이 없어진 배열이 새로 생긴 것을 볼 수 있다)

ex2)
const originArr = [ 'a', 'b', 'c', 'd', 'e' ];
const passedArr = originArr.filter( char => char !== 'a' );

console.log(originArr);
console.log(passedArr);

실행 결과('a'가 제거된 것을 볼 수 있다)

😋 배열에서 내가 원하지 않는 값을 제거하고(솎아내고) 새로운 배열을 생성한다.
map()과 마찬가지로 정말 정말 많이 쓰인다. 꼭 알아둬야할 helper다.

👉 자세한 내용은 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

 

Array.prototype.filter()

The filter() method creates a new array with all elements that pass the test implemented by the provided function.

developer.mozilla.org

 

'JavaScript > Built-in Method etc.' 카테고리의 다른 글

Math.random()  (0) 2020.01.18
Math.ceil()  (0) 2020.01.18
Array.prototype.map()  (0) 2020.01.11
Array.prototype.push()  (0) 2020.01.06
Array.prototype.pop()  (0) 2020.01.04
728x90

기존 배열(array)에 어떠한 function(연산)을 적용한 후 새로운 array를 만들고 싶을 때 사용하는 helper method
(for loop같은 반복문을 이용하고 싶지 않을 때)

💻Example Code

ex1)
const originArr = [ 1, 2, 3, 4, 5 ];
const populatedArr = originArr.map( num => num * 2 );

console.log(originArr);
console.log(populatedArr);

실행 결과(기존 array는 그대로 있다)

ex2)

const originArr = [ '1', '2', '3', '4', '5' ];
const populatedArr = originArr.map( charNum => Number(charNum) );

console.log(originArr);
console.log(populatedArr);

실행 결과(String이 Number로 변경된 것을 볼 수 있다)

😋 map()의 괄호 안에 내가 원하는 function을 넣고, 기존 array에 있는 모든 값(element)를 불러와 실행시킨다.
굉장히 자주 쓰이는 helper method로써 꼭 알아둬야할 helper다. ex2)와 같이 String -> Number로 변경시키고 싶을 때도 자주 사용한다.

👉 자세한 내용은 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

 

Array.prototype.map()

The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.

developer.mozilla.org

 

'JavaScript > Built-in Method etc.' 카테고리의 다른 글

Math.ceil()  (0) 2020.01.18
Array.prototype.filter()  (0) 2020.01.11
Array.prototype.push()  (0) 2020.01.06
Array.prototype.pop()  (0) 2020.01.04
Array.prototype.unshift()  (0) 2020.01.04
728x90

✨ 주어진 array에서 찾고자하는 element의 index를 반환, 없다면 -1을 반환하는 helper method
(index는 가장 먼저 발견된 element 기준으로 반환된다)

💻Example Code

const arr = 'gamgongsa';

console.log( arr.indexOf('a') );
console.log( arr.indexOf('g') );
console.log( arr.indexOf('z') );

실행 결과('a'의 index는 1, 'g'의 index는 0, 'z'는 없기 때문에 -1)

😋 긴 문자열이 주어지고, 여기서 내가 원하는 알파벳이 있는지 없는지를 확인하고자 할 때 쓰기 좋은 helper method
알파벳 찾기(Find alphabet) 알고리즘 문제를 풀 때 사용했다.

👉 자세한 내용은 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf

 

Array.prototype.indexOf()

The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.

developer.mozilla.org

 

'JavaScript > Built-in Method etc.' 카테고리의 다른 글

Array.prototype.unshift()  (0) 2020.01.04
String.fromCharCode()  (0) 2020.01.01
String.prototype.match()  (0) 2019.12.31
String.charCodeAt()  (0) 2019.12.31
new String()  (0) 2019.12.29
728x90

✨ 내가 찾고자하는 Pattern(character or string etc)을 찾기에 유용한 helper method
(Pattern은 사실 Regular Expression(정규표현식)이지만 쉽게 표현하기 위해 사용하였다)

💻Example Code

const str = 'Hi There!!';
const matches = str.match(/[aeiou]/gi);

console.log( matches );
console.log( matches ? matches.length : 0 )

실행 결과(match된 내용과 배열의 길이)

😋 특히, 특정 문자열을 검색하는 알고리즘 문제를 풀거나, 개발을 할때 매우 유용하다. (단, RegExp를 잘 안다는 전제하에)
Vowels Algorithm(모음 찾기) 문제를 풀 때 잘 사용했다.

👉 자세한 내용은 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match

 

String.prototype.match()

The match() method retrieves the result of matching a string against a regular expression.

developer.mozilla.org

 

'JavaScript > Built-in Method etc.' 카테고리의 다른 글

String.fromCharCode()  (0) 2020.01.01
Array.prototype.indexOf()  (0) 2020.01.01
String.charCodeAt()  (0) 2019.12.31
new String()  (0) 2019.12.29
new Array()  (0) 2019.12.29
728x90

✨ Array의 모든 index에 값을 한 번에 채워주거나, 원하는 구간만큼 값을 채워줄 수 있는 helper method

(e.g., arr.fill(false) or arr.fill(0, 2, 4)) 왼쪽처럼 Array의 모든 값을 false로 채우거나, index 2부터 3까지 0을 채워줄 수 있다.
(Array.prototype.slice()와 마찬가지로 구간을 지정할 때, end-1까지 진행된다는 점을 명심하자)

💻Example Code

const arr = [ 1, 2, 3, 4, 5, 6 ];

console.log( arr.fill(0, 1, 3) );

실행 결과(index 1부터 3까지 지정했지만, 2까지 변한 것을 볼 수 있다)

😋 매우 큰 Array의 값을 한 번에 초기화 해줄 때, 또는 원하는 index 구간만큼 값을 바꿔줄 때 매우 유용하다.
백준 4673번 셀프 넘버(Self Number)문제를 풀 때 사용했다.

👉 자세한 내용은 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/fill

 

Array.prototype.fill()

The fill() method changes all elements in an array to a static value, from a start index (default 0) to an end index (default array.length). It returns the modified array.

developer.mozilla.org

 

'JavaScript > Built-in Method etc.' 카테고리의 다른 글

new Array()  (0) 2019.12.29
Array.prototype.메소드() 만들기  (0) 2019.12.29
String.prototype.replace()  (0) 2019.12.29
Object.keys() & Object.values()  (0) 2019.12.29
Array.prototype.sort()  (0) 2019.12.28
728x90

✨ 문자 또는 숫자를 순서대로 정렬할 때 사용하는 helper method

(e.g., strArr.sort() or numArr.sort((a, b) => a - b)) 문자를 sort 할 때, 10이 넘어가는 숫자를 sort할 때, 왼쪽처럼 사용법이 다르다.
Numbers는 Strings으로 변환되기 때문에, Unicode order에 따라 80이 9보다 앞에 위치한다.

💻Example Code

const strArr = [ 'c', 'b', 'a' ];
const numArr = [ 3, 33, 2, 22, 1, 11 ];

console.log( strArr.sort() );
console.log( numArr.sort() ); // For Example
console.log( numArr.sort((a,b) => a - b) );

실행 결과( 2번째 결과는 Number를 그냥 sort() 했을 때 결과이다)

😋 Anagrams(철자 순서를 바꾼 말) Algorithm에서 유용하게 사용 가능하며, 다양한 상황에서 사용 가능하다.

✔ sort((a, b) => a - b)로 숫자가 정렬되는 것을 Test 해보자

const numArr = [ 3, 2, 1, 11, 22 ,33 ];

function compare(a, b) {
console.log('a:'+a);
console.log('b:'+b);
return a - b; }

a가 b보다 작아서 negative가 나오는 경우 a는 b보다 낮은 숫자의 index를 갖고, 0은 변화 없음, 0보다 크면 a는 b보다 높은 index를 갖게 되는 식으로 정렬된다. 아마 선택 정렬(Selection Sort)과 비슷한 방식이 아닐까 생각해본다.

👉 자세한 내용은 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

 

Array.prototype.sort()

The sort() method sorts the elements of an array in place and returns the sorted array. The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values.

developer.mozilla.org

 

'JavaScript > Built-in Method etc.' 카테고리의 다른 글

String.prototype.replace()  (0) 2019.12.29
Object.keys() & Object.values()  (0) 2019.12.29
String.prototype.toLowerCase() & toUpperCase()  (0) 2019.12.28
Array.prototype.includes()  (0) 2019.12.26
Array.prototype.every()  (0) 2019.12.24
728x90

✨ Array에 내가 입력한 값(String or Number etc.)이 포함되어 있는지 확인할 때 사용하는 helper method

(e.g., strArr.includes('a')) 왼쪽처럼 strArr이라는 Array에 'a'가 있다면 true, 없다면 false를 return.
Vowels(모음 찾기) Algorithm에서 유용하게 사용하였다.

 

💻Example Code

const strArr = [ 'a', 'b', 'c' ];

console.log( strArr.includes('a') );

실행 결과( 'a'가 포함되어있기 때문에 true 출력 )

😋 Vowels(모음 찾기) Algorithm을 풀 때, 주어진 String에서 모음(a, e, i, o, u)이 몇 개인지 찾을 때 매우 유용하다.
더 활용된 내용은 Algorithm 카테고리의 Vowels(모음 찾기) Algorithm을 참고하시면 됩니다. 

👉 자세한 내용은 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes

'JavaScript > Built-in Method etc.' 카테고리의 다른 글

Array.prototype.sort()  (0) 2019.12.28
String.prototype.toLowerCase() & toUpperCase()  (0) 2019.12.28
Array.prototype.every()  (0) 2019.12.24
Array.prototype.reduce()  (0) 2019.12.24
Array.prototype.join()  (0) 2019.12.24
728x90

✨직접 작성한 reducer function을 주입하여, 배열(array)의 여러 값을 하나씩 다루고, 최종적으로 single value를 도출해낸다.

(e.g., arr.reduce((acc, val) => acc += val)) 왼쪽처럼 기본적으로 첫 번째 argument는 accumulator, 두 번째 argument는 Current Value이며, 그 외에 세 번째 argument는 Current Index이며, reduce()의 두 번째 arugument에 initialValue(초기값)을 작성하여 acc에 초기값을 지정하는 것도 가능하다.
Reverse Int(or String)와 palindrome(회문 구조) 등 다양한 로직에서 유용하다.

💻Example Code

const numArr = [ 1, 2, 3, 4 ];
const strArr = [ 'b', 'c', 'd', 'e' ];

console.log(numArr.reduce((acc, num) => (acc = num + acc), 10));
console.log(strArr.reduce((rev, char) => (rev = char + rev), 'a'));

실행 결과(10+10=20, a+bcde를 거꾸로하면 edcba)

😋 배열의 모든 값을 간단하게 더하고 싶을 때, 배열의 문자를 거꾸로 정렬하고 싶을 때 등 다양한 기능에서 활용이 가능하다.

👉 자세한 내용은 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

'JavaScript > Built-in Method etc.' 카테고리의 다른 글

Array.prototype.includes()  (0) 2019.12.26
Array.prototype.every()  (0) 2019.12.24
Array.prototype.join()  (0) 2019.12.24
Array.prototype.reverse()  (0) 2019.12.24
Number.prototype.toString()  (0) 2019.12.24
728x90

✨ string을 integer(number)로 바꿔주는 helper method

Reverse Int(숫자 거꾸로 바꾸기) Algorithm에서 유용하게 사용했다.
(string 변환 후 다시 integer로 되돌려야하기 때문이다)

💻Example Code
✅ String와 Number를 비교하는 코드로 작성한다.

const str = '24';

console.log( parseInt(str) );
console.log( str );
console.log( typeof parseInt(str) );
console.log( typeof str );

실행 결과(Number, String) - VS Code Node.js 기준

😋 Reverse Int (숫자 거꾸로 바꾸기) Algorithm을 다룰 때, string 변환 후 최종값을 number로 되돌리기 위해 사용한다.

👉 자세한 내용은 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt

'JavaScript > Built-in Method etc.' 카테고리의 다른 글

Array.prototype.reverse()  (0) 2019.12.24
Number.prototype.toString()  (0) 2019.12.24
Math.sign()  (0) 2019.12.24
Array.prototype.slice()  (0) 2019.12.23
Math.floor()  (0) 2019.12.23
728x90

✨number 의 부호를 알아내기 위한 helper method

기본적으로 양수(positive) 또는 음수(negative) 1을 반환하며(+/- 1), 괄호 안에 0을 넣는다면 +/- 0을 반환한다.
(양수는 +로 표기하지 않고 생략한다)
Reverse Int(숫자 거꾸로 바꾸기) Algorithm에서 유용하게 사용했다.
(number를 string으로 바꿔 다루는 경우, 최종값은 number로 반환해야 하기 때문에 부호를 되찾을 때 사용한다)

💻Example Code

const num = -24;

console.log( Math.sign(num) );

실행 결과 (-1)

😋 Reverse Int algorithm을 다룰 때, test case로 주어진 number값을 string으로 변환 후 순서를 뒤바꿔 줘야한다.
따라서, 마지막 결과값을 return 해줄 때, Math.sign(test case값)을 곱해주면 본래의 부호를 손쉽게 다시 되찾을 수 있다.

👉 자세한 내용은 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign

'JavaScript > Built-in Method etc.' 카테고리의 다른 글

Number.prototype.toString()  (0) 2019.12.24
Global.parseInt()  (0) 2019.12.24
Array.prototype.slice()  (0) 2019.12.23
Math.floor()  (0) 2019.12.23
Number.prototype.toFixed()  (0) 2019.12.22

+ Recent posts