2017-02-24 134 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哎呀!我以为他们都是一样的! –