[JavaScript] 배열 특정원소 삭제

2020. 1. 26. 17:09·Web/Javascript

 

 

1. Array 생성자 함수 Prototype에  Remove 메소드 정의

 

splice method 사용하여 정의한 Array.prototype.remove 메소드

 

 

 

맹점이 하나 있다.

index 0 1 2 3 4 5 6 7 8 9
value 19 24 56 60 71 68 40 80 91 100

 

50이하의 원소는 삭제해야되는데 대체 왜 24는 살아남았는가?

(19와 40은 정상적으로 삭제되었다.)

 

remove가 일어날 때마다 배열이 재정렬 되기 때문이다. 즉 for loop 1번째 싸이클에서

19가 삭제되면 배열상태는 다음과같아진다.

index 0 1 2 3 4 5 6 7 8
value 24 56 60 71 68 40 80 91 100

원래 index 1에 해당하던 원소 '24'가 index 0으로 당겨진다.

 

(자료구조 및 알고리즘을 공부한 사람은 알겠지만 이 방법은 구데기다.)

∵ 시간 복잡도가 O(N)에 해당하는 배열 크기에 비례해서 수행 속도가 느려지기 때문.

 

[해결방법]

for loop을 역으로 돌린다.

 

 

index를 배열 끝부터 역순으로 시작하면 이 문제를 해결할 수 있다.

 

이방법은 정상적인 Output을 내놓을 뿐, 위와 마찬가지로 시간복잡도는 구데기다..

뭐 오리지널 배열은 태생적으로 특정 위치 삽입삭제 선형적 시간복잡도를 띌 수 밖에 없다..

 

 

 

2. filter 사용

 

Filter는 콜백함수로서 파라미터가 함수이다.

splice와는 다르게 기존의 배열의 원소를 조작하는 것이 아니라 아예 새로운 배열을 생성한다.

 

이름 그대로 각 배열의 원소를 필터링 하는 함수다. 

true를 반환하면 요소를 유지하고, false를 반환하면 버린다.
마찬 가지로 시간복잡도는 O(N)으로 여타 방법과 다를게 없다.

callbak함수 Parameter name Description
element(value) 처리할 현재 원소
index 처리할 원소의 index
array filter를 호출한 배열

 

filtered_array라는 함수가 새로 생성된다.

 

 

 

 

3. When to Use What to Use?

 

조건식이 까다로울 때 => prototype remove Customzing

조건이 단순할 때 => filter method

 

 

 

 

부록: 원소가 객체일 때 중복제거

보통 중복제거를 위해 Set() 객체를 많이 사용하지만 원소가 객체일 경우엔 불가능하다.

JS는 배열의 인덱스가 곧 Key 이기 때문에 Value 가 같아도 Key 가 달라지기 때문이다.

 

filter, map을 통해 트릭을 걸어 중복제거하는 방법이 있다.

이름이 같은 챔프들을 중복제거하는 코드 filter와 map을 활용한다.

 

 

 


4. Reference

 

9 Ways To Remove 🗑️ Elements From A JavaScript Array 📇[Examples]

Removing & Clearing Items From JavaScript arrays can be confusing. Splice, substring, substr, pop, shift & filter can be used. Learn how they differ and work.

love2dev.com

 

 

Array vs Set vs Map vs Object — Real-time use cases in Javascript (ES6/ES7)

The internet is a great place to find information, but there is one teeny-tiny problem. You are on a boat in the middle of a deep blue sea…

codeburst.io

 

저작자표시 (새창열림)

'Web > Javascript' 카테고리의 다른 글

[javascript] style property handling error  (0) 2020.02.22
DOM 문서 객체 모델  (0) 2020.02.21
[Javascript] typeof vs constructor  (0) 2020.01.25
Javascript Prototype  (0) 2020.01.24
JavaScript constructor, instanceof  (0) 2020.01.24
'Web/Javascript' 카테고리의 다른 글
  • [javascript] style property handling error
  • DOM 문서 객체 모델
  • [Javascript] typeof vs constructor
  • Javascript Prototype
M_Falcon
M_Falcon
  • M_Falcon
    Falcon
    M_Falcon
  • 전체
    오늘
    어제
    • 분류 전체보기 (432)
      • Web (16)
        • Nodejs (14)
        • Javascript (23)
        • FrontEnd (4)
      • DataBase (39)
        • Fundamental (1)
        • Redis (4)
        • PostgreSQL (10)
        • NoSQL (4)
        • MySQL (9)
        • MSSQL (3)
        • Error (4)
      • Algorithm (79)
        • Algorithm (문제풀이) (56)
        • Algorithm (이론) (23)
      • JVM (65)
        • Spring (13)
        • JPA (5)
        • Kotlin (13)
        • Java (24)
        • Error (7)
      • 기타 (70)
        • Kafka (3)
        • Kubernetes (3)
        • Docker (13)
        • git (19)
        • 잡동사니 (27)
      • 재테크 (11)
        • 세무 (4)
        • 투자 (3)
        • 보험 (0)
      • BlockChain (2)
        • BitCoin (0)
      • C (32)
        • C (10)
        • C++ (17)
        • Error (3)
      • Low Level (8)
        • OS (3)
        • 시스템 보안 (5)
      • 네트워크 (3)
      • LINUX (30)
        • Linux (26)
        • Error (4)
      • 저작권과 스마트폰의 이해 (0)
      • 생각 뭉치 (6)
      • 궁금증 (2)
      • Private (4)
        • 이직 경험 (0)
        • 꿈을 찾아서 (1)
      • Android (21)
        • OS (4)
  • 블로그 메뉴

    • 홈
    • WEB
    • 알고리즘
    • DataBase
    • Linux
    • Mobile
    • C
    • 방명록
  • 링크

    • github
  • 공지사항

  • 인기 글

  • 태그

    android
    알고리즘
    ubuntu
    Kotlin
    kafka
    Bitcoin
    algorithm
    java
    database
    프로그래머스
    C++
    javascript
    Spring
    JPA
    PostgreSQL
    docker
    백준
    Git
    linux
    Programmers
  • hELLO· Designed By정상우.v4.10.3
M_Falcon
[JavaScript] 배열 특정원소 삭제
상단으로

티스토리툴바