我有一个像
这样的对象数组[ {"id":0,"start":0,"duration":117,"slide":4,"view":0},
{"id":0,"start":0,"duration":12,"slide":1,"view":0},
{"id":0,"start":0,"duration":8,"slide":3,"view":0},
{"id":0,"start":0,"duration":7,"slide":2,"view":0}
];
我希望得到3个具有前3个持续时间值的对象。
答案 0 :(得分:2)
您可以使用Array#sort
对它们进行排序,降序并取前三个元素。
var array = [{ id: 0, start: 0, duration: 7, slide: 2, view: 0 }, { id: 0, start: 0, duration: 12, slide: 1, view: 0 }, { id: 0, start: 0, duration: 117, slide: 4, view: 0 }, { id: 0, start: 0, duration: 8, slide: 3, view: 0 }],
top3duration = array.sort(function (a, b) {
return b.duration - a.duration;
}).slice(0, 3);
console.log(top3duration);
.as-console-wrapper { max-height: 100% !important; top: 0; }
答案 1 :(得分:1)
yourArray.sort(function(a,b){
return b.duration - a.duration;
}).splice(0,3);
console.log(yourArray); // Will give top 3 objects of high duration.
但是你的mainArray会被修改。如果你想要那些作为新数组然后去切片(0,3)并分配给一个新的数组作为[Fallenreaper的]答案
答案 2 :(得分:1)
var myList = [ {"id":0,"start":0,"duration":117,"slide":4,"view":0},
{"id":0,"start":0,"duration":12,"slide":1,"view":0},
{"id":0,"start":0,"duration":8,"slide":3,"view":0},
{"id":0,"start":0,"duration":7,"slide":2,"view":0}
];
outList = myList.sort(function(a,b){ return b.duration - a.duration; }).slice(0,3);
return outList;
答案 3 :(得分:0)
我将通过几个简单的步骤来完成你的工作。
var myList = [ {"id":0,"start":0,"duration":117,"slide":4,"view":0},
{"id":0,"start":0,"duration":12,"slide":1,"view":0},
{"id":0,"start":0,"duration":8,"slide":3,"view":0},
{"id":0,"start":0,"duration":7,"slide":2,"view":0}
];
outList = myList.sort(function(a,b){ return b.duration - a.duration; }).slice(0,3);
return outList;