去重
var arr = [{
id: 1,
name: "张三",
sex: "girl",
}, {
id: 2,
name: "李四",
sex: "girl",
}, {
id: 3,
name: "王五",
sex: "boy",
}, {
id: 4,
name: "钱六",
sex: "boy",
},];
// 方法1:利用reduce方法遍历数组,reduce第一个参数是遍历需要执行的函数,第二个参数是item的初始值
var resultArr;
var obj = {};
resultArr = arr.reduce(function (item, next) {
obj[next.sex] ? '' : obj[next.sex] = true && item.push(next);
return item;
}, []);
console.log(resultArr);
// 方法2:利用对象访问属性的方法,判断对象中是否存在sex
var result = [];
var obj = {};
for(var i =0; i<arr.length; i++){
if(!obj[arr[i].sex]){
result.push(arr[i]);
obj[arr[i].sex] = true;
}
}
console.log(result);
过滤/筛选
var arr = [{
id: 1,
name: "张三",
sex: "girl",
}, {
id: 3,
name: "王五",
sex: "boy",
}, {
id: 4,
name: "钱六",
sex: "boy",
},];
arr=arr.filter((item)=>{
return item.sex=="boy"
});
console.log(arr)
判断数组的所有元素全部相等
function isAllEqual(array){
if(array.length>0){
return !array.some(function(value,index){
return value !== array[0];
});
}else{
return true;
}
}
var arr=["1","","1"];
console.log(isAllEqual(arr))