Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.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
Javascript 从具有基于属性名的对象的数组中删除n项_Javascript_Arrays - Fatal编程技术网

Javascript 从具有基于属性名的对象的数组中删除n项

Javascript 从具有基于属性名的对象的数组中删除n项,javascript,arrays,Javascript,Arrays,我这里有一个数组: result = [{ID:"97",answerA:"Apple", answerB:"Chair",category:"MEAT"} , {ID:"97",answerA:"Apple", answerB:"Chair",category:"MEAT"}]; 等等 到目前为止,我的数组只包含5个类别中的20个项目-到目前为止 这使得每个类别有4个项目 我希望使用我的数组,使其包含: 类别中的4项=蔬菜 该类别的3个项目=食品 3类物品=海鲜 3类物品=肉类 类别中的2项

我这里有一个数组:

result = [{ID:"97",answerA:"Apple", answerB:"Chair",category:"MEAT"} , {ID:"97",answerA:"Apple", answerB:"Chair",category:"MEAT"}];
等等

到目前为止,我的数组只包含5个类别中的20个项目-到目前为止 这使得每个类别有4个项目

我希望使用我的数组,使其包含:

类别中的4项=蔬菜 该类别的3个项目=食品 3类物品=海鲜 3类物品=肉类 类别中的2项=一般

根据上述规则,让我的数组只包含15项的最佳方法是什么

PS:当然,新的、重新排序的数组会遗漏5项


我曾想过在数组中循环,并使用IF/Else语句来使用一个新的,但我希望看到实现这一点的最佳和最简单的方法。

最干净的imo将使用array.filter和counters来获得所需的确切类别

// these are the categories and their allowed maxCounts
var counts = {
  "Vegetables": {maxCount: 4, count: 0},
  "Fingerfood": {maxCount: 3, count: 0},
  //...
};

// filtered is the reduced array containing just the ones you need
var filtered = result.filter(function(_item) {
  var c = counts[_item.category];

  // include only if allowed as per counts
  if(c && c.count < c.maxCount) { c.count++; return true; }

  return false;
});
附言:

根据需要填写计数规则集 计数中的类别名称应与结果中的类别名称的大小写匹配
@FlorianGl,呃,有没有可能有一个更全面的答案和一些解释?如果我想给出答案,我会写一个答案:我只是想指出,每个人都有自己最好的方式。对于一些人来说,这是一个代码较少的代码,对于其他人来说,这是最可读的代码,aso。当我想到一个答案时,techfoobar的答案突然出现了。在我看来,这是一个很好的解决方案,我也会使用它;您需要维护项目的顺序吗?