programing

TypeScript에서 어레이 항목을 삭제하려면 어떻게 해야 합니까?

easyjava 2023. 2. 28. 23:52
반응형

TypeScript에서 어레이 항목을 삭제하려면 어떻게 해야 합니까?

TypeScript에서 작성한 어레이가 있으며 이 어레이에는 키로 사용하는 속성이 있습니다.키가 있는 경우 어떻게 항목을 제거할 수 있습니까?

JavaScript와 같은 방법으로.

delete myArray[key];

그러면 요소가 다음과 같이 설정됩니다.undefined.

다음 기능을 사용하는 것이 좋습니다.

const index = myArray.indexOf(key, 0);
if (index > -1) {
   myArray.splice(index, 1);
}
let foo_object; // Itemitem(object here) to remove
this.foo_objects = this.foo_objects.filter(obj => return obj !== foo_object);

ES6에서는 다음 코드를 사용할 수 있습니다.

removeDocument(doc){
   this.documents.forEach( (item, index) => {
     if(item === doc) this.documents.splice(index,1);
   });
}

이 솔루션은 다음과 같습니다.

onDelete(id: number) {
    this.service.delete(id).then(() => {
        let index = this.documents.findIndex(d => d.id === id); //find index in your array
        this.documents.splice(index, 1);//remove element from array
    });

    event.stopPropagation();
}

let departments는 배열입니다.이 배열에서 항목을 제거하려고 합니다.

departments: string[] = [];

 removeDepartment(name: string): void {
    this.departments = this.departments.filter(item => item != name);
  }

를 사용할 수 있습니다.splice메서드를 사용하여 요소를 제거합니다.

예를 들어 이름을 가진 배열이 있는 경우arr다음을 사용합니다.

arr.splice(2, 1);

따라서 여기서 인덱스 2가 있는 요소가 시작점이 되고 인수 2가 삭제할 요소의 수를 결정합니다.

지정된 배열의 마지막 요소를 삭제하는 경우arr다음 작업을 수행합니다.

arr.splice(arr.length-1, 1);

그러면 마지막 요소가 삭제된 상태로 arr이 반환됩니다.

예:

var arr = ["orange", "mango", "banana", "sugar", "tea"];
arr.splice(arr.length-1, 1)
console.log(arr); // return ["orange", "mango", "banana", "sugar"]

이것은 오브젝트 배열에서 속성별로 오브젝트를 제거하기 위한 간단한 라이너입니다.

delete this.items[this.items.findIndex(item => item.item_id == item_id)];

또는

this.items = this.items.filter(item => item.item_id !== item.item_id);

이건 나한테 효과가 있었어.

어레이:

DummyArray: any = [
    { "id": 1, "name": 'A' },
    { "id": 2, "name": 'B' },
    { "id": 3, "name": 'C' },
    { "id": 4, "name": 'D' }
]

기능:

remove() {
    this.DummyArray = this.DummyArray.filter(item => item !== item);
}

주의: 이 함수는 어레이에서 모든 개체를 삭제합니다.배열에서 특정 개체를 삭제하려면 다음 방법을 사용합니다.

remove(id) {
    this.DummyArray = this.DummyArray.filter(item => item.id !== id);
}

어레이에서 지정된 개체를 제거해야 하고 다음 사항을 확인하려면 이 옵션을 사용합니다.

  • 리스트가 재초기화되지 않았습니다.
  • 어레이 길이가 올바르게 업데이트되었습니다.
    const objWithIdToRemove;
    const objIndex = this.objectsArray.findIndex(obj => obj.id === objWithIdToRemove);
    if (objIndex > -1) {
      this.objectsArray.splice(objIndex, 1);
    }

배열에서 요소를 제거하기 위한 Typescript/Javascript의 여러 옵션.스플라이스는 최적의 옵션입니다.

  1. 새 개체를 생성하지 않고 인라인으로 삭제합니다.
  2. 어레이의 길이가 올바르게 갱신됩니다(공백의 특수한 요소를 사용하지 말아 주세요).

다음은 스플라이스 함수를 사용하여 객체 배열의 일부 필드를 기반으로 객체를 삭제하는 예입니다.

const persons = [
 {
   firstName :'John',
   lastName :'Michel'
  },
  {
   firstName :'William',
   lastName :'Scott'
  },  
  {
   firstName :'Amanda',
   lastName :'Tailor'
  }
]

console.log('Before Deleting :'+JSON.stringify(persons));
console.log('Deleting William:');
persons.splice(persons.findIndex(item => item.firstName === 'William'),1);
console.log('After Deleting William'+JSON.stringify(persons));

let a: number[] = [];

a.push(1);
a.push(2);
a.push(3);

let index: number = a.findIndex(a => a === 1);

if (index != -1) {
    a.splice(index, 1);
}

console.log(a);

TypeScript 확산 연산자(...)를 사용하여 응답합니다.

// Your key
const key = 'two';

// Your array
const arr = [
    'one',
    'two',
    'three'
];

// Get either the index or -1
const index = arr.indexOf(key); // returns 0


// Despite a real index, or -1, use spread operator and Array.prototype.slice()    
const newArray = (index > -1) ? [
    ...arr.slice(0, index),
    ...arr.slice(index + 1)
] : arr;

Typescript를 사용한 다른 솔루션:

let updatedArray = [];
for (let el of this.oldArray) {
    if (el !== elementToRemove) {
        updated.push(el);
    }
}
this.oldArray = updated;

어레이 확장 방식을 추가하려고 합니다.

interface Array<T> {
      remove(element: T): Array<T>;
    }

    Array.prototype.remove = function (element) {
      const index = this.indexOf(element, 0);
      if (index > -1) {
        return this.splice(index, 1);
      }
      return this;
    };
function myFunction(ID){ 
let index = this.myArray.findIndex(d => d.ID === ID); //find index in your array
        console.log('index==',index);
        if (index > -1) {
          console.log('remaving at',index);
          this.myArray.splice(index, 1);//remove element from array
        }
}

주의: 어레이에는 ID라는 속성이 있어야 합니다.그렇지 않으면 -1이 반환되며, 이는 찾을 수 없음을 의미합니다.

목록 또는 배열의 인덱스 또는 위치를 먼저 가져온 다음 루프를 사용하여 현재 배열을 임시 목록에 할당하고 불필요한 항목을 필터링하여 원하는 항목을 원래 배열로 저장할 수 있습니다.

removeItem(index) {
    var tempList = this.uploadFile;
    this.uploadFile = [];

    for (var j = 0; j < tempList.length; j++) {
      if (j != index)
        this.uploadFile.push(tempList[j]);
    }
  }

로직을 구현할 수 있습니다.filter ★★★★★★★★★★★★★★★★★」includes

const checkAlpha2Code = ['BD', 'NZ', 'IN']

let countryAlpha2Code = ['US', 'CA', 'BD', 'NZ', 'AF' , 'AR' , 'BR']


/**
 * Returns the modified array countryAlpha2Code 
 * after removing elements which matches with the checkAlpha2Code
 */
countryAlpha2Code = countryAlpha2Code.filter(alpha2code => {
    return !checkAlpha2Code.includes(alpha2code);
});
console.log(countryAlpha2Code)
// Output: [ 'US', 'CA', 'AF', 'AR', 'BR' ]


// Resetting the values again
countryAlpha2Code = ['US', 'CA', 'BD', 'NZ', 'AF' , 'AR' , 'BR']


/**
 * Returns the modified array countryAlpha2Code 
 * which only matches elements with the checkAlpha2Code
 */
countryAlpha2Code = countryAlpha2Code.filter(alpha2code => {
    return checkAlpha2Code.includes(alpha2code);
});

console.log(countryAlpha2Code)
// Output: [ 'BD', 'NZ' ]

라는 이 많다remove메서드는 빌트되어 있지 않습니다.을 검토해 주세요.Set어레이 대신 - 다음과 같습니다.add ★★★★★★★★★★★★★★★★★」delete이치노

Abdus Salam Azad answer와 비슷하지만 //https://love2dev.com/blog/javascript-remove-from-array/에서 어레이를 파라미터로 전달합니다.

function arrayRemove(arr:[], value:any) { 
    
    return arr.filter(function(ele){ 
        return ele != value; 
    });
}
_.pull(array,'a'); 

lib lodash https://lodash.com/docs/4.17.15#pull 를 사용하여
료료: :

import _ from 'lodash';
const allTagList = ['a','b','b']
_.pull(allTagList, b);
console.log(allTagList) // result: ['a']

PS: Lodash는 많은 오퍼레이터를 제공하고 있으며, 단순히 코드를 사용하기 위해 선택되었습니다.https://lodash.com

언급URL : https://stackoverflow.com/questions/15292278/how-do-i-remove-an-array-item-in-typescript

반응형