简体   繁体   English

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

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

I have an array of objects in Javascript that look like this: 我在Javascript中有一个对象数组,如下所示:

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

If that Array size is bigger than 10, I would like to remove those objects which area (width*height) are smaller. 如果该数组大小大于10,我想删除那些区域(宽度*高度)较小的对象。 So, if there are 20 objects, remove the 10 which area are smaller among the rest. 因此,如果有20个对象,则删除其中10个区域较小的区域。

How could I do this? 我怎么能这样做?

Right now what I do is have a threshold in order to filter the objects. 现在我所做的是有一个阈值来过滤对象。 So I do this: 所以我这样做:

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

But this is not what I want. 但这不是我想要的。 I don't want a static threshold, I just want to remove those which area is smaller than the rest top 10. 我不想要一个静态阈值,我只想删除哪个区域小于其余前十名。

You can sort your array first by area and then use slice to leave only 10 bigger. 您可以先按区域对数组进行排序,然后使用slice仅留下10个更大的数组。 Something like this: 像这样的东西:

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);

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

You could sort the array and then set its length to 10. 您可以对数组进行排序,然后将其长度设置为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;

Note that this only works if you don't care if the array elements get reordered. 请注意,这只适用于您不关心数组元素是否重新排序的情况。

http://jsfiddle.net/g9Hk7/ http://jsfiddle.net/g9Hk7/

One other possibility, if you need to keep them in order is this somewhat strange little bit here: 另一种可能性,如果你需要保持它们的顺序,这有点奇怪:

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);

This modifies the original array, but you can change that by replacing the last line with 这会修改原始数组,但您可以通过替换最后一行来更改它

}, clone(arr));

using some appropriate clone function, perhaps this: 使用一些适当的克隆功能,也许这个:

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

Obviously if you wanted to turn this into a function, you could generalize the 10 , and it would pretty easy to abstract from area into an arbitrary function on your objects as well. 显然,如果你想将它变成一个函数,你可以概括10 ,并且很容易从area抽象到对象上的任意函数。

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

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