มีอาร์เรย์จำนวนเต็มที่เรียงจากน้อยไปมาก ต้องจัดกลุ่มโดยที่สมาชิกในกลุ่มเดียวกันต่างกันไม่เกิน 1 และแต่ละกลุ่มต้องมีสมาชิกมากกว่า 1 ตัว
ตัวอย่าง: [1,2,3,5,6,7,10,12,17,18] → [[1,2,3], [5,6,7], [17,18]]
ตัวอย่างโค้ด
const arr = [1, 2, 3, 5, 6, 7, 10, 12, 17, 18];
const groupNear = (arr = []) => {
const res = [];
for (let ind = 0; ind < arr.length; ind++) {
let value = arr[ind];
if (arr[ind - 1] + 1 === value) {
res[res.length - 1].push(value);
} else if (value + 1 === arr[ind + 1]) {
res.push([value]);
}
}
return res;
};
console.log(groupNear(arr));
ผลลัพธ์
ค่าที่แสดงในคอนโซลจะเป็นดังนี้:
[ [ 1, 2, 3 ], [ 5, 6, 7 ], [ 17, 18 ] ]