简体   繁体   English

Lodash的“细分”系列

[英]“Segmentize” collection with lodash

  • I have a collection col1 我有一个收藏col1

     var col1 = [1, 8, 9, 10, 2, 54, 7]; 
  • I have another collection col2 我还有另一个收藏集col2

     var col2 = [1, 8, 23, 9, 46, 10, 2, 54, 78, 7] 

    ...that I know it contains every element of col1 , plus some other elements ...我知道它包含col1每个元素以及其他一些元素

  • I want to obtain this : 我想获得这个:

     var col3 = [ [1, 8], [9], [10, 2, 54], [7] ] 

    col1 "splitted", "segmentized" by col2 col1col2 “分割”,“分段”

I'd like to use lodash functions for conciseness, but if someone brings an answer as vanilla JS, I'll accept the answer, and traduct it to lodash as an edit. 为了简洁起见,我想使用lodash函数,但是如果有人以香草JS的形式给出答案,我会接受答案,并将其引入lodash进行编辑。

NB: I use ints for readability on SO, but my real collection contains objects. 注意:我使用ints来提高SO的可读性,但我的实际收藏包含对象。
NB2: each element is unique in both collections NB2:每个元素在两个集合中都是唯一的
NB3: elements that are common to both collections are in the same order NB3:两个集合共有的元素以相同的顺序

I think a plain Javascript algorithm will be shorter, faster, and easier to understand here: 我认为普通的Javascript算法在此处将更短,更快并且更容易理解:

var l = [],
    col3 = [l],
    i = 0;
for (var j=0; j<col2.length; j++)
    if (col1[i] == col2[j])
        l.push(col1[i++]);
    else
        col3.push(l = []);

Same thing, less concise, using a lodash loop: 使用lodash循环,同样的事情,不太简洁:

var col1Pointer = 0;
var segment = [];
var col3 = [];
col3.push(segment);

_.foreach(col2, function(col2Item) {
  var col1Item = col1[col1Pointer];
  if (col1Item == col2Item) {
    col1Pointer++;
    segment.push(col1Item);
  } else {
    segment = [];
    col3.push(segment);
  }
});

I can't think of a proper pure lodash way - there just is no appropriate method. 我想不出适当的纯lodash方式-只是没有适当的方法。 But we could write one ourselves: 但是我们可以自己写一个:

_.mixin({
    splitOn: function(arr, callback, thisArg) {
        if (!arr.length) return [];
        callback = _.callback(callbac, thisArg);
        var seg = [],
            res = [seg];
        for (var i=0; i<arr.length; i++)
            if (callback(arr[i], i, arr))
                res.push(seg = [])
            else
                seg.push(arr[i]);
        return res;
    }
});

and then use it like 然后像

var col3 = _.splitOn(col2, _.ary(_.partial(_.includes, col1), 1));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM