js 数组去重小技巧 Intro 今天遇到一个问题,需要对数据进行去重,想看一下有没有什么比较方便的方法,果然有些收获。 Question 问题描述: 我有一个这样的数据: 要实现根据 Project
js 数组去重小技巧
[
{
"ProjectId": "94147992363ef910","ProjectName": "新梅太古城中粮天悦澜庭","ProjectAddress": "曲阜路966弄"
},{
"ProjectId": "c5b6ce1988dd2af7","ProjectName": "新梅共和城","ProjectAddress": "广中西路99弄"
},"ProjectAddress": "广中西路99弄"
}
]
[
{
"ProjectId": "94147992363ef910","ProjectAddress": "广中西路99弄"
}
]
//
var arr = [1,4];
var result = new Array();
var filterArr = new Array();
for (var i = 0; i < info.length; i++) {
for (var k = 0; k < filterArr.length; k++) {
if (filterArr[i] == arr[i]) {
continue;
}
}
// 或者使用 indexOf 判断
//if (filterArr[i].indexOf(arr[i]) > -1) {
// continue;
//}
filterArr.push(arr[i]);
result.push(arr[i]);
}
// filter
arr = arr.filter(function (value,index,array) {
return array.indexOf (value) == index;
});
// es6
arr = arr.filter( (value,array) => array.indexOf (value) == index);
//
var info = [
{
"ProjectId": "94147992363ef910","ProjectAddress": "广中西路99弄"
}
];
function filter() {
var filterArr = [];
var result = [];
for (var i = 0; i < info.length; i++) {
for (var k = 0; k < filterArr.length; k++) {
if (filterArr[i] == info[i].ProjectId) {
continue;
}
}
filterArr.push(info[i].ProjectId);
result.push(info[i]);
}
return result;
}
var arr = [1,4];
console.log(arr); // [1,4]
arr = Array.from(new Set(arr));
console.log(arr);// [1,4]
//
info = info.filter((s => a => !s.has(a.ProjectId) && s.add(a.ProjectId))(new Set));
info = info.filter((s => a => !s.has(a.ProjectId) && s.add(a.ProjectId))(new Set));