数组
# 将数组转为对象(指定key)
const arrayToObject = (arr, key) => arr.reduce((a, b) => ({ ...a, [b[key]]: b }), {});
// eg:
arrayToObject([{id:6,name:'张三'}, {id:70,name:'里斯'}], 'id')
/*
{
"6": {
"id": 6,
"name": "张三"
},
"70": {
"id": 70,
"name": "里斯"
}
}
*/
# 数组去重
export const unique = (arr) => {
if (Array.hasOwnProperty('from')) {
return Array.from(new Set(arr));
} else {
var n = {},
r = [];
for (var i = 0; i < arr.length; i++) {
if (!n[arr[i]]) {
n[arr[i]] = true;
r.push(arr[i]);
}
}
return r;
}
}
# 随机打乱数组(洗牌算法)
export const shuffle = (arr) => {
let result = [], random;
while (arr.length > 0) {
random = Math.floor(Math.random() * arr.length);
result.push(arr[random]);
arr.splice(random, 1) ;
}
return result;
}
上次更新: 2022/08/26, 17:06:25