0
点赞
收藏
分享

微信扫一扫

JavaScript数组

蓝哆啦呀 2021-09-25 阅读 70
  1. 筛选满足条件的项
var arr = [1, 6, 9, 3, 6, 56, 7, 36];
arr.filter((item) => { return item > 6 && item < 32 });  // 输出 [9, 7]
  1. 去掉空字符、空格字符串、null、undefined
var arr = ['A', '', 'B', null, undefined, 'C', ' '];
var r = arr.filter(item => {
 return item && item.trim();  // 注:IE9(不包含IE9)以下的版本没有trim()方法
});
console.log(r); // 输出 ['A', 'B', 'C']
  1. 排序(按对象属性排序)
var fruit = [
  {id: 3, type: '苹果'},
  {id: 7, type: '草莓'},
  {id: 2, type: '梨子'},
  {id: 6, type: '凤梨'},
]
function sortById(item1, item2) {
  // 升序,如降序,反过来即可
  return item1.id - item2.id
}
console.log(fruit.sort(sortById));  

// 输出 [{id: 2, type: '梨子'}, {id: 3, type: '苹果'},{id: 6, type: '凤梨'},{id: 7, type: '草莓'}]
// array.sort() 方法是在原数组的基础上重新排序,不会生成副本。
  1. 数组去重
let arr = [1, 6, 9, 3, 6, 56, 9, 36]
let newArr = arr.reduce((pre, cur) => {
    if (!pre.includes(cur)) {
        return pre.concat(cur)
    } else {
        return pre
    }
}, [])
console.log(newArr)  // [1, 6, 9, 3, 56, 36]
举报

相关推荐

0 条评论