코딩테스트 준비(JS)

Minji·2022년 5월 12일
0

코딩테스트 연습

목록 보기
4/11

배열 추가,제거

unshift() 맨 앞에 추가
shift() 맨 앞에서 제거
push() 맨 뒤에 추가
pop() 맨 뒤에서 제거

splice

arr.splice(시작index,삭제할요소 갯수,추가할 내용)
예를 들어,

const array=[1,4,9,12]
array.splice(1,1,2,3) //arr[1]에서부터 1개지우고나서 2,3추가
console.log(array) // [1,2,3,9,12]

추가만 하려면 array.splice(1,0,2,3)
삭제만 하려면 array.splice(1,1)

split

str.split([separator[, limit]])

const str="ABC DEF GHI JK"
console.log(str.split(' ',2)) //[ 'ABC', 'DEF' ]
console.log(str.split(' ')) //[ 'ABC', 'DEF', 'GHI', 'JK' ]
  • 정규식이랑 같이 사용(공백제거)
var names = 'Harry Trump ;Fred Barney; Helen Rigby ; Bill Abel ;Chris Hand ';

console.log(names);

var re = /\s*(?:;|$)\s*/;
var nameList = names.split(re);

console.log(nameList);

substr, substring

str.substr(시작,추출갯수)
str.substr(2,3) : 2번 인덱스부터 3개

str.substring(시작,끝)
str.substring(2,3) : 2번 인덱스부터 3번 인덱스까지

filter

**array.filter((요소, index) => { })**

  • 길이 6 이상인 것만 뽑아내라 arr.filter((tmp)⇒tmp.length>=6)
  • 문자'e’ 포함된 것만 뽑아내라
const words=['spray','limit','elite','elephant']

const result=words.filter((w)=>w.includes('e'));

console.log(result)

map

const array=[1,2,3,4]
const mapArr=array.map((x)=>x*2)
console.log(mapArr) //[2,4,6,8]

filter, map

const array=[1,4,9,12]
const map1=array.map((x)=>(Number.isInteger(Math.sqrt(x)))?Math.sqrt(x):0);
const mapif=array.map((x)=>{
    if(Number.isInteger(Math.sqrt(x))){
        return Math.sqrt(x)
    }
})
const mapfilter=array.filter((x)=>Number.isInteger(Math.sqrt(x)))
.map((x)=>Math.sqrt(x))
console.log(mapfilter,map1,mapif) //[ 1, 2, 3 ] [ 1, 2, 3, 0 ] [ 1, 2, 3, undefined ]
profile
매일매일 성장하기 : )

0개의 댓글