使用兩個屬性對陣列中的值進行分組 JavaScript
我們有一個類似這樣的物件陣列:
const arr = [ { value: 12, gap: 1 }, { value: 13, gap: 1 }, { value: 14, gap: 1 }, { value: 15, gap: 1 }, { value: 19, gap: 2 }, { value: 21, gap: 1 }, { value: 22, gap: 1 }, { value: 23, gap: 1 }, { value: 27, gap: 1 }, { value: 31, gap: 4 }, { value: 35, gap: 4 }, { value: 39, gap: 4 }, { value: 43, gap: 1 }, { value: 50, gap: 1 }, { value: 51, gap: 1 }, { value: 52, gap: 1 }, { value: 55, gap: 1 }, { value: 57, gap: 1 }, ];
我們需要編寫一個函式,此函式接收此陣列,然後返回一個新陣列,其中所有連續物件的值等於上一個物件的值之和,且差距必須組合在一個子陣列中。
例如,值 12 的物件與 1 的差距,以及它的下一個值 13,因此它們必須與它們一起分組,還需與值 14 和 15 的物件分組,以此類推。
現在,既然已經理解了問題,那麼我們接下來編寫此問題的程式碼。我們將使用 Array.prototype.reduce() 方法構建所需的陣列:
範例
const arr = [ { value: 12, gap: 1 }, { value: 13, gap: 1 }, { value: 14, gap: 1 }, { value: 15, gap: 1 }, { value: 19, gap: 2 }, { value: 21, gap: 1 }, { value: 22, gap: 1 }, { value: 23, gap: 1 }, { value: 27, gap: 1 }, { value: 31, gap: 4 }, { value: 35, gap: 4 }, { value: 39, gap: 4 }, { value: 43, gap: 1 }, { value: 50, gap: 1 }, { value: 51, gap: 1 }, { value: 52, gap: 1 }, { value: 55, gap: 1 }, { value: 57, gap: 1 }, ]; const groupArray = arr => { return arr.reduce((acc, val, ind, array) => { // the accumulated data and lastIndex of accumulated data const { data, currentIndex } = acc; // the current object properties const { value, gap } = val; // the previous object properties const v = arr[ind-1]?.value; const g = arr[ind-1]?.gap; if(ind === 0 || value !== v + g){ // recording the index of last object and pushing new subarray const index = data.push([val]) - 1; return { data, currentIndex: index }; }; data[currentIndex].push(val); return { data, currentIndex }; }, { data: [], currentIndex: 0 }).data; } console.log(groupArray(arr));
結果
控制檯中的結果將是:
[ [ { value: 12, gap: 1 }, { value: 13, gap: 1 }, { value: 14, gap: 1 }, { value: 15, gap: 1 } ], [ { value: 19, gap: 2 }, { value: 21, gap: 1 }, { value: 22, gap: 1 }, { value: 23, gap: 1 } ], [ { value: 27, gap: 1 } ], [ { value: 31, gap: 4 }, { value: 35, gap: 4 }, { value: 39, gap: 4 }, { value: 43, gap: 1 } ], [ { value: 50, gap: 1 }, { value: 51, gap: 1 }, { value: 52, gap: 1 } ], [ { value: 55, gap: 1 } ], [ { value: 57, gap: 1 } ] ]
廣告