티스토리 뷰

Working log

[javascript] Array, Set 관련 예제

까오기 2021. 12. 1. 14:29

1. string to array 

const str = value.split(',')  // 구분자

2. array to string 

const str = arr.join(",")

3. array to set 

const set = new Set(arr)

4. set to array 

const arr = Array.from(set)

5. array foreach 

const arr = v.split(',');
const newArr = []
arr.forEach(element => {
	if(element) newArr.push(element.trim())
});

6. 배열에 값 추가 

// push 마지막에 추가 
arr.push(item)

// unshift 처음에 추가 
arr.unshift("하나")

7. splice 

Array.splice(position, 삭제 수, 새로운아이템...)

let numbers = ['하나', '둘', '셋'];
// 처음에 추가 
numbers.splice(0, 0, '넷')
console.log(JSON.stringify(numbers)) // ["넷","하나","둘","셋"]

// 마지막에 추가 
numbers.splice(4, 0, '다섯')
console.log(JSON.stringify(numbers)) // ["넷","하나","둘","셋","다섯"]

// 두번째 값 이후에 추가 
numbers.splice(1, 0, '여섯')
console.log(JSON.stringify(numbers)) // ["넷","여섯","하나","둘","셋","다섯"]

// 두번째 값 바꾸기 
numbers.splice(1, 1, '일곱')  // 두번째 자리에 하나 지우고 일곱을 넣는다. 
console.log(JSON.stringify(numbers)) // ["넷","일곱","하나","둘","셋","다섯"]

// 세번째 값 바꾸고 여러개 넣기  
numbers.splice(2, 1, '여덜', '아홉')
console.log(JSON.stringify(numbers)) // ["넷","일곱","여덜","아홉","둘","셋","다섯"]

// 첫번째 값 지우기 
numbers.splice(0, 1) 
console.log(JSON.stringify(numbers)) // ["일곱","여덜","아홉","둘","셋","다섯"]

// 세번째부터 2개 지우기 
numbers.splice(2, 2) 
console.log(JSON.stringify(numbers)) // ["일곱","여덜","셋","다섯"]

8. 배열에서 값 꺼내기(shift, pop)  

let numbers = ['하나', '둘', '셋'];
// 첫번째 값 꺼내기 
const first = numbers.shift()
console.log(first); // 하나 
console.log(JSON.stringify(numbers)) // ["둘","셋"]

// 마지막 값 꺼내기
const last = numbers.pop()
console.log(last); // 셋
console.log(JSON.stringify(numbers)) // ["둘"]

8. 중복 체크

checkDuplication (v) {
  const arr = v.split(',');
  const set = new Set(arr);
  if(newArr.length !== set.size) {
    return false;
  }
  return true;
},

checkDuplicationTrim (v) {
  const arr = v.split(',');
  const newArr = [];
  arr.forEach(element => {
    if(element) newArr.push(element.trim());
  });
  const set = new Set(newArr);
  // duplicate
  if(newArr.length !== set.size) {
    return false;
  }
  return true;
},

 

 

 

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함