本文主要是介绍JS篇之连续相同数据去重,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
原先数据:
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;}
这篇关于JS篇之连续相同数据去重的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!