배열에서 특정 요소를 제거하는 방법

LONGNEW·2020년 12월 28일
0

https://stackoverflow.com/questions/5767325/how-can-i-remove-a-specific-item-from-an-array

Q. How can I remove a specific item from an array?
Q. 특정 요소를 배열에서 제거하려면 어떻게 해야 하나요?

I have an array of numbers and I'm using the .push() method to add elements to it.
숫자들을 가진 배열이 있고 .push() 메소드를 이용해서 요소들을 추가하고 있습니다.
Is there a simple way to remove a specific element from an array?
특정 요소를 제거할 때 쓰는 간단한 방법이 있나요??
I'm looking for the equivalent of something like:
아래의 커맨드 같은 것을 찾고 있습니다.

array.remove(number);

I have to use core JavaScript. Frameworks are not allowed.
JavaScript 를 이용해야 합니다. 프레임 워크는 못 써요.


Find the index of the array element you want to remove using indexOf, and then remove that index with splice.
indexOf를 이용해서 특정 아이템을 찾은후, splice로 그 인덱스의 아이템을 삭제 합니다.

The splice() method changes the contents of an array by removing existing elements and/or adding new elements.
splice() 메소드는 현재 배열의 아이템을 제거하거나 새로운 요소를 추가함으로써 배열의 아이템들을 바꿉니다.

const array = [2, 5, 9];

console.log(array);

const index = array.indexOf(5);
if (index > -1) {
  array.splice(index, 1);
}

// array = [2, 9]
console.log(array); 

The second parameter of splice is the number of elements to remove.
splice의 2 번째 파라미터는 삭제할 요소의 개수입니다.
Note that splice modifies the array in place and returns a new array containing the elements that have been removed.
splice 현재 있는 배열을 수정 한 이후에 수정된 배열을 리턴합니다.


For the reason of completeness, here are functions.
기능들입니다.
The first function removes only a single occurrence (i.e. removing the first match of 5 from [2,5,9,1,5,8,5]), while the second function removes all occurrences:
첫번째의 경우엔 맨 처음 만나는 5만 삭제합니다. 두번째는 모든 5를 삭제합니다.

function removeItemOnce(arr, value) {
  var index = arr.indexOf(value);
  if (index > -1) {
    arr.splice(index, 1);
  }
  return arr;
}

function removeItemAll(arr, value) {
  var i = 0;
  while (i < arr.length) {
    if (arr[i] === value) {
      arr.splice(i, 1);
    } else {
      ++i;
    }
  }
  return arr;
}
//Usage
console.log(removeItemOnce([2,5,9,1,5,8,5], 5))
console.log(removeItemAll([2,5,9,1,5,8,5], 5))

0개의 댓글