目录
滴滴 2020年9月7日
1.求数组的每一项,作为key,在对象中对应的值
var arr = ['b','c','d','e']
let obj = {
'b':{'c':{'d':1}},'e':3
}
function getArrValue(arr,obj){
let objCopy = {}
function getKeyValue(obj){
let obj1 = JSON.parse(JSON.stringify(obj))
Object.keys(obj).forEach((item)=>{
if(typeof obj[item]=='object'){
objCopy[item]=obj[item]
obj = obj[item]
getKeyValue(obj)
}else{
objCopy[item]=obj1[item]
}
})
}
getKeyValue(obj)
arr.forEach((item)=>{
console.log(item,objCopy[item])
})
}
getArrValue(arr,obj)
2.数组flattern展开
let arr = [1,2,[3,4,[5,6]]]
function flaten(arr,depth){
let result =[];
arr.forEach(element => {
if(!Array.isArray(element)){
result.push(element)
}else{
if(depth==0){
result.push(element)
}else{
result.push(...flaten(element,depth-1))
}
}
});
return result
}
console.log(flaten(arr,1))
3.删掉字符串中出现次数最少的字符
var map = new Map();
var str ='aabbccddeee';
for(var i=0;i<str.length;i++){
if(map.get(str[i])>=1){
map.set(str[i],map.get(str[i])+1)
}else{
map.set(str[i],1)
}
}
let smallNum = str.length;
let startIndex = 0;
map.forEach(function(item){
if(item<=smallNum){
smallNum = item;
startIndex +=item
}
})
console.log(str.substr(startIndex))
4. 记住展开的层级,用-代表深度
let obj = {"name":"a","c":{"name":"c","b":{"name":"b","d":{"name":"d"}}}}
let count =1;
function getValue(obj,count){
let objKey = Object.keys(obj);
let len = objKey.length;
for(let i=0;i<len;i++){
if(typeof obj[objKey[i]]!='object'){
let temp = ''
for(var j=0;j<count;j++){
temp+='-'
}
obj[objKey[i]]=temp+obj[objKey[i]];
}else{
getValue(obj[objKey[i]],++count)
}
}
}
getValue(obj,count)
console.log(obj)
//结果为{ name: '-a',
c: { name: '--c', b: { name: '---b', d: [Object] } } }
5.对数组对象中的年龄进行分类
var obj = [
{'name':'xiaoxiao','age':10},
{'name':'test','age':10},
{'name':'xiaoxiao','age':15},
{'name':'xiaoxiao','age':12}
]
obj.sort((a,b)=>a.age-b.age)
// console.log(obj)
let newObj = {};
obj.forEach(item=>{
if(!newObj.hasOwnProperty(item.age)){
newObj[item.age] = []
newObj[item.age][0] = item
}else{
newObj[item.age].push(item)
}
})
6.实现数组乱序
let changeLocation = (arr) =>{
let len = arr.length;
let result = []
while(len>0){
let index = Math.floor(Math.random()*len)
result.push(arr[index])
arr.splice(index,1);
len = arr.length;
}
return result
}