Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/svn/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays 如果条件匹配,则typescript数组删除项_Arrays_Typescript - Fatal编程技术网

Arrays 如果条件匹配,则typescript数组删除项

Arrays 如果条件匹配,则typescript数组删除项,arrays,typescript,Arrays,Typescript,我有一个与某些字段类似的接口: 接口项{ id:编号; 名称:字符串; } 我想实现一个方法removitemswithname(items:Item[],name:string),它从给定数组中删除所有具有给定名称的项: const myItems:Item[]=[ {id:1,名称:'foo'}, {id:2,名称:'foo'}, {id:3,名称:'bar'} ]; removitemswithname(myItems,'foo'); console.log(myItems); 结果应

我有一个与某些字段类似的接口:

接口项{
id:编号;
名称:字符串;
}
我想实现一个方法
removitemswithname(items:Item[],name:string)
,它从给定数组中删除所有具有给定名称的项:

const myItems:Item[]=[
{id:1,名称:'foo'},
{id:2,名称:'foo'},
{id:3,名称:'bar'}
];
removitemswithname(myItems,'foo');
console.log(myItems);
结果应该是:

[{id: 3, name: 'bar'}]
typescript/javascript中是否有可用的方法
array.removeIf()
(如Java 8中的方法),因此我的方法可能类似于以下内容:

函数removitemswithname(项:项[],名称:字符串):void{
items.removeIf(i=>i.name==name);
}

我已经找到了这个问题,但是我需要修改原来的数组,而不是创建一个新的数组(比如
array.filter()
does)。我还想删除与条件匹配的所有项,而不仅仅是第一项。

您可以使用
Array.prototype.filter
():

const myItems=[{
id:1,
姓名:“富”
},
{
id:2,
姓名:“富”
},
{
id:3,
名称:“酒吧”
}
];

console.log(myItems.filter((item)=>item.name!=='foo'))
执行此操作的方法太多了,我建议使用
filter
函数

试试这个:

function removeItemsWithName(items: Item[], name: string): void {
  items = items.filter(i => i.name !== name);
}
我认为如果
removitemswithname
函数返回一个新数组并且不更改params值会更好

function removeItemsWithName(items: Item[], name: string): Item[] {
  return items.filter(i => i.name !== name);
}

const myItems: Item[] = [
  { id: 1, name: 'foo' },
  { id: 2, name: 'foo' },
  { id: 3, name: 'bar' }
];

const filtered = removeItemsWithName(myItems, 'foo');
console.log(filtered);
更新

您可以使用
removeIf
方法创建所有者
Collection

interface Item {
  id: number;
  name: string;
}

class MyCollection<T> {
  private items: Array<T>;

  constructor(init?: T[]) {
    this.items = init || [];
  }

  get(): T[] {
    return this.items;
  }

  removeIf(conditionFunction: (i: T) => boolean) {
    this.items = this.items.filter(i => !conditionFunction(i));
  }
}

const myItems: MyCollection<Item> = new MyCollection<Item>([
  { id: 1, name: "foo" },
  { id: 2, name: "foo" },
  { id: 3, name: "bar" }
]);

function removeItemsWithName<T extends Item>(
  items: MyCollection<T>,
  name: string
): void {
  items.removeIf(i => i.name === name);
}

removeItemsWithName(myItems, "foo");
console.log(myItems.get());
接口项{
id:编号;
名称:字符串;
}
类MyCollection{
私有项:数组;
构造函数(init?:T[]{
this.items=init | |[];
}
get():T[]{
归还此物品;
}
removeIf(条件函数:(i:T)=>布尔值){
this.items=this.items.filter(i=>!条件函数(i));
}
}
const myItems:MyCollection=新的MyCollection([
{id:1,名称:“foo”},
{id:2,名称:“foo”},
{id:3,名称:“bar”}
]);
函数removeItemsWithName(
项目:MyCollection,
名称:string
):无效{
items.removeIf(i=>i.name==name);
}
removeItemsWithName(我的项目,“foo”);
log(myItems.get());

标准解决方案是,但这将返回一个新数组:

但是,如果确实需要就地修改阵列,则必须使用以下内容:

function removeItemsWithName(items: Item[], name: string): void {
  let j = 0;
  for (let i = 0; i < items.length; i++) {
    const item = items[i];
    if (item.name !== name) {
        items[j] = item;
        j++;
    }
  }

  items.length = j;
}
或者您可以使用lodash这样的库,它有一个方便的方法:


拿一个,利用
.filter()
。更少的代码,但O(2n)

拿两个,使用老式的O(n)方式
.splice()


可能是@HereticMonkey的复制品我之前已经注意到了这个问题,但我忘了在我的问题中提到这个。我现在编辑了我的帖子来澄清它。我注意到数组问题总是比其他问题得到更多的答案:p这个问题的答案比被接受的答案多。例如,在循环中使用
splice
。@HereticMonkey感谢您引用这个,我一定错过了这个答案。如果需要改变原始数组怎么办?如
removitemswithname(…):void
@hackape overwrite原始数组值,
items=removitemswithname(myItems,'foo')
@hoangdv感谢您的回答,但覆盖原始数组不是一个选项。我需要修改给定的数组。@hoangdv如果您没有抓住要点,则需要保留原始数组引用。谢谢您的回答。很遗憾,我需要修改给定的数组,无法创建新数组。
function removeItemsWithName(items: Item[], name: string): void {
  let j = 0;
  for (let i = 0; i < items.length; i++) {
    const item = items[i];
    if (item.name !== name) {
        items[j] = item;
        j++;
    }
  }

  items.length = j;
}
function removeItemsWithName(items: Item[], name: string): void {
  for (let i = 0; i < items.length; i++) {
    if (items[i].name === name) {
      items.splice(i--, 1);
    }
  }
}
import _remove from 'lodash/remove';

function removeItemsWithName(items: Item[], name: string): void {
  _remove(items, x => x.name === name);
}
function removeItemsWithName(items: Item[], name: string): void {
  var newArray = items.filter(i => i.name !== name);
  items.length = 0; // this empty the original array
  newArray.forEach(item => { items.push(item) });
}
function removeItemsWithName(items: Item[], name: string): void {
  var index = items.length - 1;
  var predicate = i => i.name === name;
  while(index >= 0) {
    if (predicate(items[index])) {
      items.splice(index, 1)
    }
    index--;
  }
}