[英]how to sort array of objects according to a value of a specific property
如下代码所示,我有一个数组,并且将对象推入循环中。 我想做的是,根据delay属性的值对其进行排序。 我使用以下代码:
delayOfFeatures.sort((a, b) => a.delay - b.delay);
但数组不变
代码 :
delayOfFeatures.push({ progSpace: progSpace, feature: feature, delay: delay });
这是一个示例,您可以根据其中的delay
属性以升序或降序对features
数组进行排序。
class Feature { constructor(name, delay) { this._name = name; this._delay = delay; } get name() { return this._name; } get delay() { return this._delay; } } const features = [ new Feature('Feature A', 1000), new Feature('Feature C', 500), new Feature('Feature B', 50), new Feature('Feature D', 1), new Feature('Feature E', 750), ]; // Ascending by delay features.sort((a, b) => a.delay - b.delay); console.log(features); // Descending by delay features.sort((a, b) => b.delay - a.delay); console.log(features);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.