IT story

배열의 첫 번째와 마지막 요소를 제거하려면

hot-time 2020. 9. 8. 22:01
반응형

배열의 첫 번째와 마지막 요소를 제거하려면


배열에서 첫 번째와 마지막 요소를 제거하는 방법은 무엇입니까?

예를 들면 :

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

반응형