배열의 첫 번째와 마지막 요소를 제거하려면
배열에서 첫 번째와 마지막 요소를 제거하는 방법은 무엇입니까?
예를 들면 :
var fruits = ["Banana", "Orange", "Apple", "Mango"];
예상 출력 배열 :
["Orange", "Apple"]
fruits.shift(); // Removes the first element from an array and returns only that element.
fruits.pop(); // Removes the last element from an array and returns only that element.
1 레벨 전체 복사본을 만듭니다.
fruits.slice(1, -1)
원래 배열을 놓으십시오.
철자 오류를 지적 해 주신 @Tim에게 감사드립니다.
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var newFruits = fruits.slice(1, -1);
console.log(newFruits); // ["Orange", "Apple"];
여기서 -1은 배열의 마지막 요소를 나타내고 1은 두 번째 요소를 나타냅니다.
스플 라이스 방식을 사용합니다.
fruits.splice(0, 1); // Removes first array element
var lastElementIndex = fruits.length-1; // Gets last element index
fruits.splice(lastElementIndex, 1); // Removes last array element
마지막 요소를 제거하려면 다음과 같이 할 수도 있습니다.
fruits.splice(-1, 1);
참조 배열에서 마지막 항목을 제거 그것에 대한 자세한 설명을 볼 수 있습니다.
push()
배열 끝에 새 요소를 추가합니다.
pop()
배열의 끝에서 요소를 제거합니다.
unshift()
배열의 시작 부분에 새 요소를 추가합니다.
shift()
배열의 시작 부분에서 요소를 제거합니다.
배열에서 첫 번째 요소를 제거하려면 배열 arr
에서 arr.shift()
마지막 요소를 제거하려면 다음을 arr
사용하십시오.arr.pop()
Array.prototype.reduce () 사용할 수 있습니다 .
암호:
const fruits = ['Banana', 'Orange', 'Apple', 'Mango'],
result = fruits.reduce((a, c, i, array) => 0 === i || array.length - 1 === i ? a : [...a, c], []);
console.log(result);
배열에서 요소를 제거하려면 다음을 수행하십시오.
let array_splited = [].split('/');
array_splited.pop()
array_splited.join('/')
이것은 lodash _.tail
및 _.dropRight
다음 으로 수행 할 수 있습니다 .
var fruits = ["Banana", "Orange", "Apple", "Mango"];
console.log(_.dropRight(_.tail(fruits)));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
var resident_array = ["RC_FRONT", "RC_BACK", "RC_BACK"];
var remove_item = "RC_FRONT";
resident_array = $.grep(resident_array, function(value) {
return value != remove_item;
});
resident_array = ["RC_BACK", "RC_BACK"];
첫 번째 요소 제거에 Fruits.shift () 메서드를 사용했습니다. 마지막 요소에 사용 된 Fruits.pop () 메서드는 버튼 클릭을 사용한 경우 하나씩 제거합니다. Fruits.slice (시작 위치, 요소 삭제) 중간 시작에서 요소 제거를 위해 slice 메서드도 사용했습니다.
To remove the first and last element of an array is by using the built-in method of an array i.e shift()
and pop()
the fruits.shift()
get the first element of the array as "Banana" while fruits.pop()
get the last element of the array as "Mango". so the remaining element of the array will be ["Orange", "Apple"]
참고URL : https://stackoverflow.com/questions/4644139/to-remove-first-and-last-element-in-array
'IT story' 카테고리의 다른 글
Swift에서 String.Index는 어떻게 작동합니까? (0) | 2020.09.08 |
---|---|
하위 디렉터리를 포함한 코드 줄을 계산하는 방법 (0) | 2020.09.08 |
이 두 div를 나란히 배치하는 방법은 무엇입니까? (0) | 2020.09.08 |
PostgreSQL ROLE (사용자)가없는 경우 생성 (0) | 2020.09.08 |
숭고한 텍스트 2에서 코드 제외 섹션 접기 / 축소 (0) | 2020.09.08 |