1.创建一个数组,判断数组中是否存在某个值
var newarr = [ { num: 1, val: 'ceshi', flag: 'aa' }, { num: 2, val: 'ceshi2', flag: 'aa2' } ] console.log(newarr.filter(item => item.num===2 ))
2.也可以通过上面方法过滤掉num为2的留下num为1的
var newarr = [ { num: 1, val: 'ceshi', flag: 'aa' }, { num: 2, val: 'ceshi2', flag: 'aa2' } ] console.log(newarr.filter(item => item.num!=2 ))
3.去掉空数组空字符串、undefined、null
var arr = ['1','2',undefined, '3.jpg',undefined] var newArr = arr.filter(item => item) console.log(newArr) var arr = ['1','2',null, '3.jpg',null] var newArr = arr.filter(item => item) console.log(newArr) //空字符串里面不能包含空格 var arr = ['1','2','', '3.jpg',''] var newArr = arr.filter(item => item) console.log(newArr)
4.去掉数组中不符合项
var arr = [20,30,50, 96,50] var newArr = arr.filter(item => item>40) console.log(newArr)
5.过滤不符合项
var arr = ['10','12','23','44','42'] var newArr = arr.filter(item => item.indexOf('2')<0) console.log(newArr)
6.数组去重
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]
7.数组去重es6
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)]
8.数组对象去重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); // (4) [{…}, {…}, {…}, {…}]0: {id: 0, name: "小明"}1: {id: 1, name: "小张"}2: {id: 2, name: "小李"}3: {id: 3, name: "小孙"}length: 4__proto__: Array(0)
上面是“ES6 filter数组过滤八大方法总结”的全面内容,想了解更多关于 js 内容,请继续关注web建站教程。
当前网址:https://ipkd.cn/webs_81.html
workflows工作流
- 红伞伞蓝杆杆云南蘑菇群ComfyUI工作流
- 一位身着传统红色服装的女战士ComfyUI工作流
- 大黄蜂空中决战ComfyUI工作流
- 一桌精致的美食,桌上几杯白葡萄酒
- 一个漂亮的混血女孩ComfyUI工作流
- 一只可爱的飞鸟ComfyUI工作流
- 一条闪闪发光的金鱼ComfyUI工作流
- 森林里坐着一个外星人ComfyUI工作流
猜你喜欢
声明:本站提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请发送到邮箱:admin@ipkd.cn,我们会在看到邮件的第一时间内为您处理!