繁体   English   中英

从数组中删除元素,直到只有10个元素

[英]Remove elements from an array until there are just 10 elements

我在Javascript中有一个对象数组,如下所示:

[{width:100,height:50,name:"John"},{width:27,height:12,name:"John"},..]

如果该数组大小大于10,我想删除那些区域(宽度*高度)较小的对象。 因此,如果有20个对象,则删除其中10个区域较小的区域。

我怎么能这样做?

现在我所做的是有一个阈值来过滤对象。 所以我这样做:

var i = elements.length;
var threshold = 100;
while (i--) {
  if (elements[i].width * elements[i].height < threshold) {
    elements.splice(i,1);
  }
}

但这不是我想要的。 我不想要一个静态阈值,我只想删除哪个区域小于其余前十名。

您可以先按区域对数组进行排序,然后使用slice仅留下10个更大的数组。 像这样的东西:

var arr = arr.sort(function(a, b) {
    var as = a.width * a.height,
        bs = b.width * b.height;
    if (as > bs) return -1;
    if (as < bs) return 1;
    return 0; 
})
.slice(0, 10);

演示: http//jsfiddle.net/y765Z/

您可以对数组进行排序,然后将其长度设置为10。

var areas = [{width:100,height:50,name:"John"},{width:27,height:12,name:"John"},...];

areas.sort(function(a, b){ 
    return  b.height * b.width - a.height * a.width;
});

areas.length = 10;

请注意,这只适用于您不关心数组元素是否重新排序的情况。

http://jsfiddle.net/g9Hk7/

另一种可能性,如果你需要保持它们的顺序,这有点奇怪:

arr.map(function(item, index) {
    return {index: index, area: item.height * item.width};
}).sort(function(a, b) {
    return b.area - a.area;
}).slice(10).sort(function(a, b) {
    return b.index - a.index;
}).reduce(function(arr, item) {
    arr.splice(item.index, 1);
    return arr;
}, arr);

这会修改原始数组,但您可以通过替换最后一行来更改它

}, clone(arr));

使用一些适当的克隆功能,也许这个:

var clone = function(obj) {return JSON.parse(JSON.stringify(obj));};

显然,如果你想将它变成一个函数,你可以概括10 ,并且很容易从area抽象到对象上的任意函数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM