2017-02-24 76 views
0

給定一個有序數組,我想創建一個包含匹配元素數組的新2D數組。類似python的itertools.groupby數組中的匹配元素

例中的行爲:

input = ['a','a','a','a','d','e','e','f','h','h','h','i','l','m','n','r','s','s','t','u','v','y','y'] 

output = [ ['a','a','a','a'], ['d'], ['e','e'], ['f'], ['h','h','h'], ['i'], ['l'], ['m'], ['n'], ['r'], ['s','s'], ['t'], ['u'], ['v'], ['y','y']] 
+1

您可以包括'你已經在嘗試的問題javascript'? – guest271314

回答

1

你可以檢查的前身,並推到最後一項之前增加一個新的陣列。

var input = ['a', 'a', 'a', 'a', 'd', 'e', 'e', 'f', 'h', 'h', 'h', 'i', 'l', 'm', 'n', 'r', 's', 's', 't', 'u', 'v', 'y', 'y'], 
 
    output = input.reduce(function (r, a, i, aa) { 
 
     if (aa[i - 1] !== a) { 
 
      r.push([]); 
 
     } 
 
     r[r.length - 1].push(a); 
 
     return r; 
 
    }, []); 
 
    
 
console.log(output);
.as-console-wrapper { max-height: 100% !important; top: 0; }

對於非排序的項,你可以使用一個封閉在一個哈希表。

var input = ['a', 'a', 'a', 'a', 'y', 'h', 'h', 'i', 'l', 'e', 'e', 'f', 'h', 'm', 'n', 'r', 's', 'y', 'd', 's', 't', 'u', 'v'], 
 
    output = input.reduce(function (hash) { 
 
     return function (r, a) { 
 
      if (!hash[a]) { 
 
       hash[a] = []; 
 
       r.push(hash[a]); 
 
      } 
 
      hash[a].push(a); 
 
      return r; 
 
     }; 
 
    }(Object.create(null)), []); 
 
    
 
console.log(output);
.as-console-wrapper { max-height: 100% !important; top: 0; }

0

可以與參數""String.prototype.match()使用Array.prototype.join()RegExp/([a-z]+)(?=\1)\1|[^\1]/g匹配一個或多個"a"通過"z"隨後捕獲的字符,或者不捕獲基,.map().split()

var input = ['a', 'a', 'a', 'a' 
 
      , 'd', 'e', 'e', 'f' 
 
      , 'h', 'h', 'h', 'i' 
 
      , 'l', 'm', 'n', 'r' 
 
      , 's', 's', 't', 'u' 
 
      , 'v', 'y', 'y']; 
 

 
var res = input.join("").match(/([a-z]+)(?=\1)\1|[^\1]/g).map(c => c.split("")); 
 

 
console.log(res);

0

注:這會工作,即使陣列沒有排序:

var input = ['a','b','c','d','a','d','e','e','f','h','h','h','i','l','m','n','r','s','s','t','u','v','y','y']; 
 

 

 
function group(arr) { 
 
    var hash = {}; 
 
    return arr.reduce(function(res, e) { 
 
    if(hash[e] === undefined)   // if we haven't hashed the index for this value 
 
     hash[e] = res.push([e]) - 1; // then hash the index which is the index of the newly created array that is initialized with e 
 
    else        // if we have hashed it 
 
     res[hash[e]].push(e);   // then push e to the array at that hashed index 
 
    return res; 
 
    }, []); 
 
} 
 

 
console.log(group(input));

+0

['Array#reduce'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce)沒有'thisArg'。 –

+0

@NinaScholz哎呀!我以爲他們都是一樣的! –