[英]Function that returns unique values for certain property in object array, in order
This is my data这是我的数据
$scope.Reports = [
{ Id: 1, Name: 'Report One', Year: 2016, Month: 5 },
{ Id: 2, Name: 'Report Core', Year: 2016, Month: 5 },
{ Id: 3, Name: 'Report Alpha', Year: 2016, Month: 3 },
{ Id: 4, Name: 'Report Moon', Year: 2015, Month: 5 },
{ Id: 5, Name: 'Report Sky', Year: 2015, Month: 2 }
];
$scope.desc = function (arr) {
return $('min')
($('map')(arr, '-Year'));
};
I am trying to retrieve the list of the Year
values in descending order, so I can use them in an orderBy
filter in AngularJs.我正在尝试按降序检索
Year
值的列表,因此我可以在 AngularJs 的orderBy
过滤器中使用它们。
So for the data above, I'd want [2016, 2015]
.所以对于上面的数据,我想要
[2016, 2015]
。
How can I get that?我怎么能得到那个?
I don't know if Angular has something specific to help with this, but in JavaScript it's fairly straight-forward: Determine the unique list of years, then sort them in descending order.我不知道 Angular 是否有一些特定的东西可以帮助解决这个问题,但在 JavaScript 中它是相当简单的:确定唯一的年份列表,然后按降序对它们进行排序。
Here's an example doing it by building an object with keys for the years:这是一个示例,它通过使用多年来的键构建对象来实现:
var data = [ { Id: 1, Name: 'Report One', Year: 2016, Month: 5 }, { Id: 2, Name: 'Report Core', Year: 2016, Month: 5 }, { Id: 3, Name: 'Report Alpha', Year: 2016, Month: 3 }, { Id: 4, Name: 'Report Moon', Year: 2015, Month: 5 }, { Id: 5, Name: 'Report Sky', Year: 2015, Month: 2 } ]; var years = getUnique(data, "Year").sort(function(a, b) { // Sorts numerically in descending order return b - a; }); function getUnique(array, prop) { var obj = Object.create(null); array.forEach(function(entry) { obj[entry[prop]] = true; }); return Object.keys(obj); } // Show result document.body.innerHTML = JSON.stringify(years);
I split getUnique
off into a function in case you need to reuse it for other similar things.我将
getUnique
拆分为一个函数,以防您需要将它重用于其他类似的事情。
In an ES2015 environment, you might use set
instead of an object (and arrow functions).在 ES2015 环境中,您可以使用
set
而不是对象(和箭头函数)。
在 angular 中使用 loadash。
_.reverse(_.sortedUniq(_.map(a,'Year')))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.