我们有一个这样的对象数组-
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 } ] ]