2017-02-24 6 views
0

ソートされた配列があれば、一致する要素の配列を含む新しい2次元配列を作成したいと考えています。 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

あなたは一致するRegExp/([a-z]+)(?=\1)\1|[^\1]/gでパラメータ""String.prototype.match()Array.prototype.join()を使用することができる1つまたは複数の"z""a"捕獲文字が続き、またはグループ、.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 oops!彼らはすべて同じであると思った! –

関連する問題