2种格式数据排重
一、对数组中对象直接排重,序号据用","分割
/**
* 对数组中对象的某一个属性进行排重
* 实现原理: 新建2个数组,一个保存去重后的数据(List),一个保存属性(key),遍历data数组,查找List数组中
*是否存在key的值,如果存在,对序号进行处理,不存在就保存在List中,输出List
* [listPaiChong 数据排重]
* @param {[type]} data [要排重的数组]
* @param {[type]} key [数组对象中属性]
* @return {[type]} [Array]
*/
function listPaiChong(data, key) {
var List = []; // 去重后的数据
var item = []; //临时保存的数据(key的值)
for (var i = 0; i < data.length; i++) {
var value = item.indexOf(data[i][key]);
if (value === -1) {
item.push(data[i][key]);
List.push(data[i]);
} else {
//取最早的重复数据
var number = List[value].NUMBER; //保存重复的序号
List[value].NUMBER = number + "," + List[value].NUMBER;
}
}
return List;
}
二、数据排重为特定格式
var testS = "1,2,3,5,7,9,14,15,16,17,19,21,22,24,26,27,29,30,32,33,34,37";
console.log(testS);
var testArray = testS.split(",");
var resultArray = ["0"];
for (var i = 0; i < testArray.length; i++) {
var index = parseInt(testArray[i]),
resultLastIndex = resultArray[resultArray.length - 1];
if (resultLastIndex.indexOf("-") > 0) {
var resultLastIndexArray = resultLastIndex.split("-");
resultLastIndex = resultLastIndexArray[resultLastIndexArray.length - 1];
if (index - (parseInt(resultLastIndex)) === 1) {
resultArray[resultArray.length - 1] = resultLastIndexArray[0] + "-" + index;
} else {
resultArray.push(index.toString());
}
} else {
if (index - (parseInt(resultLastIndex)) === 1) {
resultArray[resultArray.length - 1] = resultLastIndex + "-" + index;
} else {
resultArray.push(index.toString());
}
}
}
if (resultArray[0].indexOf("0-") === 0) {
var headArray = resultArray[0].split("-");
for (var i = 0; i < testArray.length - 1; i++) {
if (parseInt(testArray[i]) > parseInt(headArray[0]) && parseInt(testArray[i]) <= parseInt(headArray[1])) {
resultArray[0] = parseInt(testArray[i]) === parseInt(headArray[1]) ? headArray[1] : testArray[i] + "-" + headArray[1]
break;
}
}
} else {
resultArray.splice(0, 1);
}
console.log(resultArray.join(","));
网友评论