我有一些属性的元素列表,例如
doc.title = 'some title'
doc.category = 'book'
doc.year = '2016'
其他可能的类别可以是纸张,文章等。
现在,假设有两个按钮“按类别排序”和“按年份排序”。
单击“按类别排序”时,列表应为:
Book
1. book 1
2. book 2
Paper
1. paper 1
2. paper 2
Article
1. article 1
2. article 2
当点击“按年份排序”按钮时
2016
1.
2.
3.
2015
1.
2.
等等。
我想做到这一点,同时保持html页面的尺寸尽可能小。请让我知道完成此操作的最佳方法是什么。
像这样的东西应该使您入门-该代码带有注释注释(在操作中查看):
// convert array of objects into a Map grouped and ordered by supplied key
function group(items, key) {
// get unique values for grouping key
const unique = [
...new Set(items.map(item => item[key]))
];
// will be ascending by default
unique.sort();
// sorting all of the results by title field
const sortFn = (a, b) => a.title > b.title;
const sortItems = (val) => {
// filters the result set to items sharing the current group field value
let sorted = items.filter(item => item[key] === val);
// sort by title
sorted.sort(sortFn);
return sorted;
}
// reduce to a Map (which preserves insertion order and maintains the group key sorting)
return unique.reduce((map, cur) => map.set(cur, sortItems(cur)), new Map());
}
// testing it out
data = [{
title: 'foo',
category: 'book',
year: 2016,
}, {
title: 'bar',
category: 'book',
year: 2016,
}, {
title: 'blah',
category: 'paper',
year: 2010,
}, {
title: 'idk',
category: 'paper',
year: 2015,
}]
group(data, 'category'); // Map {"book" => [Object, Object], "paper" => [Object, Object]}
group(data, 'year'); // Map {2010 => [Object], 2015 => [Object], 2016 => [Object, Object]}
为了进行显示,可以使用for...of
解构:
for (let [category, items] of group(data, 'category')) {
console.log(`
<div class="item">
<h3>${category}</h3>
<ol>${items.map(item => `<li>${item.title}</li>`).join('')}</ol>
</div>
`);
}
请注意,即使我在整个过程中都使用了ES6,也可以很容易地对其进行重构,以实现向后兼容。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句