- 筛选满足条件的项
var arr = [1, 6, 9, 3, 6, 56, 7, 36];
arr.filter((item) => { return item > 6 && item < 32 }); // 输出 [9, 7]
- 去掉空字符、空格字符串、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']
- 排序(按对象属性排序)
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() 方法是在原数组的基础上重新排序,不会生成副本。
- 数组去重
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]