2017-06-22 191 views
-2

如何可以通過分裂值的陣列是這樣的:陣列分割基於值

[0, 1, 2, 0, 0, 0, 1, 0] => [[0, 1, 2], [0], [0], [0, 1], [0]]

我正在使用lodash紀錄片,但有點出於現在的想法。有沒有辦法與_.groupBy做到這一點? 感謝您的回答。

+0

拆分基於consecutivity? – Li357

+1

你到目前爲止嘗試過什麼? – Luca

+0

是否有你想要分割的模式? –

回答

4

使用本機JavaScrip Array#reduce方法。

var data = [0, 1, 2, 0, 0, 0, 1, 0], 
 
    last; 
 

 
var res = data.reduce(function(arr, v) { 
 
    // check the difference between last value and current 
 
    // value is 1 
 
    if (v - last == 1) 
 
    // if 1 then push the value into the last array element 
 
    arr[arr.length - 1].push(v) 
 
    else 
 
    // else push it as a new array element 
 
    arr.push([v]); 
 
    // update the last element value 
 
    last = v; 
 
    // return the array refernece 
 
    return arr; 
 
    // set initial value as empty array 
 
}, []) 
 

 
console.log(res);

1

下面是ES2015(原ES6)簡潔的解決方案。

const newArray = []; 
 

 
[0, 1, 2, 0, 0, 0, 1, 0].forEach(item => item === 0 ? 
 
    newArray.push([0]) : 
 
    newArray[newArray.length - 1].push(item) 
 
); 
 

 
console.log(newArray);

1

你可以使用每一個新的陣列發現的零值,否則追加到結果集的最後一個陣列。

var array = [0, 1, 2, 0, 0, 0, 1, 0], 
 
    result = array.reduce(function (r, a) { 
 
     if (a) { 
 
      r[r.length - 1].push(a); 
 
     } else { 
 
      r.push([a]); 
 
     } 
 
     return r; 
 
    }, []); 
 

 
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

1

如果你有當你遇到一個零,你可以求助於 此代碼啓動一個新的陣列,希望它不會出現vodoo編程。

var x = [0, 1, 2, 0, 0, 0, 1, 0]; 

x.join("")   /* convert the array to a string */ 
.match(/(0[^0]*)/g) /* use a regex to split the string 
         into sequences starting with a zero 
         and running until you encounter 
         another zero */ 
.map(x=>x.split("")) /* get back the array splitting the 
         string chars one by one */ 

我假設數組元素只是一個數字長,而0是每個子數組的開始。

取出一個數字假設不惜以這樣代碼:

var x = [0, 1, 2, 0, 12, 0, 0, 1, 0]; 
var the_regexp = /0(,[1-9]\d*)*/g; 

x.join(",")    /* convert the array to a comma separated 
          string */ 
.match(the_regexp)  /* this regex is slightly different from 
          the previous one (see the note) */ 
.map(x=>x.split(",")) /* recreate the array */ 

在此方案中,我們用逗號的數組元素分開,讓我們來看看正則表達式:

/0意味着每個子陣列啓動用0,/是匹配

,[1-9]\d*該子圖案匹配的整數,如果它有在前面的逗號的開始;第一個數字不能爲0,另一個可選數字沒有這個限制。因此,我們匹配,1,200,9,549302387439209

我們必須在子數組中包括所有連續的非零數字,我們發現(,[1-9]\d*)*也許沒有,因此第二個*

`/ g'關閉RegExp。 g表示我們希望所有的比賽,而不僅僅是第一個。

如果你喜歡一個oneliner:

x.join(",").match(/0(,[1-9]\d*)*/g).map(x=>x.split(',')); 

,或者,如果你喜歡的預ECMA2015函數表達式語法:

x.join(",").match(/0(,[1-9]\d*)*/g).map(function(x){return x.split(',');});