- a、b两个数组的交集与差集
let a = new Set([1,2,3,4,5,6])
let b = new Set([4,5,6,7,8,9])
let inter = new Set(Array.from(new Set([...b].filter(x => a.has(x)))))
let differ = Array.from(new Set([...b].filter(x => !inter.has(x))))
<!--a与b的交集-->
console.log(inter)
{4, 5, 6}
<!--b与inter差集-->
console.log(differ)
[7, 8, 9]
- 筛选出数组中符合条件的元素列表
let attr = [{name:1,status:1},{name:2,status:2},{name:3,status:3}]
let newList = attr.filter(item => {
return item.status === 1
})
console.log(newList)
[{name:1,status:1}]
- 筛选出数组中符合条件的元素
- 返回符合条件的元素
let attr = [{name:1,status:1},{name:2,status:2},{name:3,status:3}]
let obj = attr.find(item => {
return item.status === 1
})
console.log(obj)
{name:1,status:1}
- 返回符合条件元素的位置
var fruits = ["Banana", "Orange", "Apple", "Mango"]
var a = fruits.indexOf("Apple")
console.log(a)
2
- 返回符合条件元素的位置 2
var fruits = ["Banana", "Orange", "Apple", "Mango"]
var a = fruits.findIndex((value)=>value=='Banana')
console.log(a)
0
- 取出数组的元素属性 拼成新数组(字符串)
principalFn (list) {
let l = list.map((li) => {
return li.name
})
return l.join()
}
- 判断数组中是否包含某一个元素
- 简单数组
let a = [1,2,3,4,5,6,7]
let key1 = a.includes(1)
let key2 = a.includes(999)
console.log(key1)
true
console.log(key2)
false
- 包含对象元素的数组
let a = [{a:1},{a:2},{a:3},{a:4},{a:5},{a:6},{a:7}]
let num1 = a.some(item =>{
return item.a>3
})
let num2 = a.some(item =>{
return item.a>9
})
console.log(num1)
true
console.log(num2)
false
- 数组去重
- 数组内是字符串、数字、布尔值、undefined、null
let attr = [1,2,3,4,'1','2','3','4',1,2,3,4,'1','2','3','4',undefined,undefined,undefined,null,null,null]
console.log(new Set(attr)) // Set(10){1, 2, 3, 4, "1", "2", "3", "4", undefined, null}
console.log(Array.from(new Set(attr))) // [1, 2, 3, 4, "1", "2", "3", "4", undefined, null]
console.log(...new Set(attr)) // 1 2 3 4 "1" "2" "3" "4" undefined null
let person = [{id:1,status:1},{id:2,status:2},{id:3,status:3},{id:1,status:1},{id:1,status:4},{id:5,status:5}]
let obj = {};
let peon = person.reduce((cur,next) => {
obj[next.id] ? "" : obj[next.id] = true && cur.push(next);
return cur;
},[]) //设置cur默认类型为数组,并且初始值为空的数组
console.log(peon);
// [{id:1,status:1},{id:2,status:2},{id:3,status:3},{id:5,status:5}]
let a = [1,2,3,4,56,9]
let b = [1,2,3,4,100]
console.log(new Set([...a,...b]))
- 数组对象排序
var person = [{name:"Rom",age:12},{name:"Bob",age:22},{name:"Ma",age:5},{name:"Tony",age:25}]
person.sort((a,b)=>{ return a.age-b.age})
person.sort((a,b)=>{ return b.age-a.age})