1.创建一个数组,判断数组中是否存在某个值
// 1.创建一个数组,判断数组中是否存在某个值
var newarr = [
{ num: 1, val: 'ceshi111', flag: 'aa111' },
{ num: 2, val: 'ceshi222', flag: 'aa222' }
];
var filter = newarr.filter(item => item.num===2 );
console.log(filter)
** 2.创建一个数组,过滤掉num为2的留下num为1的**
var newarr = [
{ num: 1, val: 'ceshi111', flag: 'aa111' },
{ num: 2, val: 'ceshi222', flag: 'aa222' }
];
var filter = newarr.filter(item => item.num!=2 );
console.log(filter)
3 创建一个数组,去掉空数组空字符串、undefined、null
var arr1 = ['1','2',undefined, '3.jpg',undefined]
var newArr1 = arr1.filter(item => item)
console.log(newArr1)
var arr2 = ['1','2',null, '3.jpg',null]
var newArr2 = arr2.filter(item => item)
console.log(newArr2)
//空字符串里面不能包含空格
var arr3 = ['1','2','', '3.jpg','']
var newArr3 = arr3.filter(item => item)
console.log(newArr3)
4 创建一个数组,去掉数组中不符合项
var arr = [20,30,50, 96,50]
var newArr = arr.filter(item => item>40)
console.log(newArr)
5 创建一个数组,数组去重
var arr = [1, 2, 2, 3, 4, 5, 5, 6, 7, 7,8,8,0,8,6,3,4,56,2];
var arr2 = arr.filter((x, index,self)=>self.indexOf(x)===index)
console.log(arr2); //[1, 2, 3, 4, 5, 6, 7, 8, 0, 56]
6 数组对象去重es6
let person = [
{id: 0, name: "小明"},
{id: 1, name: "小张"},
{id: 2, name: "小李"},
{id: 3, name: "小孙"},
{id: 1, name: "小周"},
{id: 2, name: "小陈"},
];
let obj = {};
let peon = person.reduce((cur,next) => {
obj[next.id] ? "" : obj[next.id] = true && cur.push(next);
return cur;
},[])
//设置cur默认类型为数组,并且初始值为空的数组
console.log(peon);
7 .数组去重
var arr=[1,2,1,'1',null,null,undefined,undefined,NaN,NaN]
let res=Array.from(new Set(arr));//{1,2,"1",null,undefined,NaN}
//or let newarr=[...new Set(arr)]
console.log(res);