原先数据:
const data = [
{ deviceID: '1', value: 'a' },
{ deviceID: '1', value: 'b' },
{ deviceID: '1', value: 'b1' },
{ deviceID: '1', value: 'b2' },
{ deviceID: '2', value: 'c' },
{ deviceID: '2', value: 'd' },
{ deviceID: '2', value: 'd1' },
{ deviceID: '2', value: 'd2' },
{ deviceID: '3', value: 'e' },
];
转换之后:
function filterData(data) {
let index = 0;
let deviceIdList = []; //设备id列表,用于判断是否相邻
let findList = []; //二维数组
for (let i = 0; i < data.length; i++) {
if (deviceIdList.includes(data[i].deviceID)) {
findList[index] = [...findList[index], data[i]];
} else {
deviceIdList = [];
findList[i] = [data[i]];
deviceIdList.push(data[i].deviceID);
index = i;
}
}
findList = findList.filter(item => item.length);
// 保留第一次和最后一次 拍平数组
let filterdata = [];
findList.forEach((item, index) => {
if (item.length > 2) {
let ls = [item[0], item[item.length - 1]];
filterdata.push(...ls);
} else {
filterdata.push(...item);
}
});
return filterdata;
}