Es6
js对数组进行分类
const people = [
{ name: 'Alice', age: 21 },
{ name: 'Max', age: 20 },
{ name: 'Jane', age: 20 }
]
const groupedPeople = {
20: [
{ name: 'Max', age: 20 },
{ name: 'Jane', age: 20 }
],
21: [
{ name: 'Alice', age: 21 }
]
}
function groupBy(objectArray, property) {
return objectArray.reduce(function (acc, obj) {
let key = obj[property]
if (!acc[key]) {
acc[key] = []
}
acc[key].push(obj)
return acc
}, {})
}
const groupedPeople = groupBy(people, 'age')
js比较两个数组是否相同
JSON.stringify([1,2,3].sort()) === JSON.stringify([3,2,1].sort());
[1,2,3].sort().toString() === [3,2,1].sort().toString();
isAllEqual (array) {
if (array.length > 0) {
return !array.some(function (value, index) {
return value.sort().toString() !== array[0].sort().toString()
})
}
return true
}
对象去重
![d 对象去重在这里插入图片描述](https://img-blog.csdnimg.cn/20191015201527168.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQwOTI0MDM0,size_16,color_FFFFFF,t_70)
数组去重
![在这里插入图片描述](https://img-blog.csdnimg.cn/20191015201625709.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQwOTI0MDM0,size_16,color_FFFFFF,t_70)
数组map
![在这里插入图片描述](https://img-blog.csdnimg.cn/20191015201640628.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQwOTI0MDM0,size_16,color_FFFFFF,t_70)
将数组打乱*
arr.sort( () => Math.random() - 0.5)
sort
![在这里插入图片描述](https://img-blog.csdnimg.cn/20191221114838966.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQwOTI0MDM0,size_16,color_FFFFFF,t_70)
排序字母或汉字
const arr = ['我', '小', '大', '车']
const value = arr.sort((a, b) => {
return b.localCompare(a)
})
![在这里插入图片描述](https://img-blog.csdnimg.cn/20200318105522805.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQwOTI0MDM0,size_16,color_FFFFFF,t_70)
通过数据匹配相应的数据
const arr = [3, 1]
const obj = [
{ id: 1, name: 'hahah' },
{ id: 2, name: 'wwww' },
{ id: 3, name: 'xxxx' },
]
const newArr = []
for (let item of arr) {
for (let options of obj) {
if (options.id == item) {
newArr.push(options)
}
}
}
console.log('newArr', newArr)
改变数据的key值
let data = [{
"adcode": "110100",
"city": "北京市",
"id": 234
}, {
"adcode": "120100",
"city": "天津市",
"id": 235,
"child": [
{
"adcode": "110100",
"city": "北京市",
"id": 234
}, {
"adcode": "110100",
"city": "北京市",
"id": 234
},
]
}]//旧key到新key的映射
let keyMap = {
"adcode": "value",
"city": "name"
}
function tt(data) {
data.forEach(item => {
let obj = item
for (let key in obj) {
let newKey = keyMap[key]
if (newKey) {
obj[newKey] = obj[key]
delete obj[key]
}
}
if (item.child) {
tt(item.child)
}
})
return data
}
console.log(tt(data))