簡體   English   中英

在下划線 js 中分組

[英]group by in underscore js

{
     collectionId: 1,
     category: 'a',
     collectionType: 'typea'
 }, {
     collectionId: 1,
     category: 'a',
     collectionType: 'typea'
 }, {
     collectionId: 1,
     category: 'b',
     collectionType: 'typea'
 }, {
     collectionId: 2,
     category: 'b',
     collectionType: 'typeb'
 }, {
     collectionId: 2,
     category: 'b',
     collectionType: 'typeb'
 },

我如何做以下用例:

A) 2 本書具有相同的收藏類型和相同的類別:兩本書應該組合在一起並顯示為該類別的收藏

B) 兩本收藏類型相同但類別不同的​​書:兩本書應歸為一組,並在稱為“我的收藏”的單獨書架中顯示為收藏。 (此書架是書架上其他類別的補充)

C) 3 本書具有相同的收藏類型,但 2 本書具有相同的類別,而 1 本書具有不同的類別:所有 3 本書應組合在一起並作為收藏顯示在稱為“我的收藏”的單獨書架中。 (此書架是書架上其他類別的補充)

var LIMIT = 2,
    C_LIMIT = 3;

// A
_(coll)
.chain()
.groupBy(i => i.collectionType.concat(i.category))
.findWhere(i => i.length > LIMIT)
.first(LIMIT)
.value();

// B
_(coll)
.chain()
.groupBy('collectionType')
.mapObject(i => _(i).indexBy('category'))
.values()
.findWhere(i => _(i).keys().length >= LIMIT)
.values()
.first(LIMIT)
.value();

// C
_(coll)
.chain()
.groupBy('collectionType')
.mapObject(function(i) {
    return _(i)
    .chain()
    .groupBy('category')
    .values()
    .map(v => _(v).first(LIMIT))
    .sortBy('length')
    .reverse()
    .flatten()
    .first(C_LIMIT)
    .value()
})
.values()
.findWhere(i => i.length === C_LIMIT)
.value(); 

 var coll = [{ collectionId: 1, category: 'a', collectionType: 'typea' }, { collectionId: 1, category: 'a', collectionType: 'typea' }, { collectionId: 1, category: 'b', collectionType: 'typea' }, { collectionId: 2, category: 'b', collectionType: 'typeb' }, { collectionId: 2, category: 'b', collectionType: 'typeb' }]; var LIMIT = 2, C_LIMIT = 3, el = document.getElementById('result'); var a = _(coll) .chain() .groupBy(i => i.collectionType.concat(i.category)) .findWhere(i => i.length > LIMIT) .first(LIMIT) .value(); var b = _(coll) .chain() .groupBy('collectionType') .mapObject(i => _(i).indexBy('category')) .values() .findWhere(i => _(i).keys().length >= LIMIT) .values() .first(LIMIT) .value(); var c = _(coll) .chain() .groupBy('collectionType') .mapObject(function(i) { return _(i) .chain() .groupBy('category') .values() .map(v => _(v).first(LIMIT)) .sortBy('length') .reverse() .flatten() .first(C_LIMIT) .value() }) .values() .findWhere(i => i.length === C_LIMIT) .value(); el.innerHTML = _([a, b, c]).map(x => JSON.stringify(x)).join('<br><br>');
 <script src="http://underscorejs.org/underscore-min.js"></script> <div id="result"></div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM