生成指定长度且元素为 1~10 的数组
Array.from({length: 10}, (d,i) => i + 1);
Array.from(new Array(11).keys()).slice(1)
判断数组中某一个 key 的所有值是否相等
function isAllEqual(array: Array<any>, key: string) {
return array.every(item => item[key] === array[0][key]);
}
计算一维数组中元素的出现次数
list.reduce((pre, item) => {
// in 关键字:判断一个属性名是否存在于对象或数组中;
if(item in pre) {
pre[item]++;
}else {
pre[item] = 1;
}
return pre;
}, {})
抽取数组对象里面的某个属性重新组成数组
list.reduce((pre, item) => {
return [...pre, item[key]];
}, []);
数组对象根据某个属性值去重
function uniqueArr(arr) {
const res = new Map();
return arr.filter((a) => !res.has(a.id) && res.set(a.id,1));
}
判断两个数组对象中某个属性组成的数组是否相同
let arrA = [{id: 1, name: 'aa1'},{id: 2, name: 'aa2'}];
let arrB = [{id: 3, name: 'bb1'}];
const idA = new Set(arrA.reduce((pre, item) => [...pre, item.id], []));
const idB = new Set(arrB.reduce((pre, item) => [...pre, item.id], []));
const totalId = new Set([...idA, ...idB]);
const ifSame = idA.size === totalId .size;
数组以另一个数组的某个字段为排序基准排序
// 两个数组对象中均有id属性,其中数组B要以数组A中的id为基准排序
const arrA = [{id: 2},{id: 4},{id: 1},{id: 3}];
const arrB = [{id: 4},{id: 2},{id: 3},{id: 1}];
const sortBase = arrA.reduce((pre, item) => [...pre, item.id], []);
arrB.sort((a,b) => {
return sortBase.indexOf(a.id) - sortBase.indexOf(b.id);
})
数组对象按某个属性值分组
/**
** @param array: 对象数组
** @param groupParam: 对象数组中对象的键名
** @return result:按键名分组过的对象数组
*/
function arrayGroupBy(array, groupParam) {
const arr = array;
const groupedArr = arr.reduce((pre, item) => {
const groupName = item[groupParam];
pre[groupName] = [...pre[groupName] || [], item];
return pre;
}, {});
const result = Object.keys(groupedArr).map(key=>{
const obj = {
name: key,
value: groupedArr[key]
};
return obj;
});
return result;
}
// demo
const arr = [
{name: '王二', age: 18, role: '销售'},
{name: '张三', age: 20, role: '店长'},
{name: '李四', age: 18, role: '经理'},
{name: '许五', age: 24, role: '店长'},
{name: '六六', age: 23, role: '销售'},
];
const result = arrayGroupBy(arr, 'role');
数组对象中按多个属性值分组
/**
** @param array: 对象数组
** @param props: 对象数组中对象的键名
** @return result:按键名分组过的对象数组
*/
function arrayGroup(array, props) {
const getGroupedItems = (item) => {
const returnArray = [];
for (let i = 0; i < props.length; i++) {
returnArray.push(item[props[i]]);
}
return returnArray;
};
const groups = {};
for (let i = 0; i < array.length; i++) {
const arrayRecord = array[i];
const group = JSON.stringify(getGroupedItems(arrayRecord));
groups[group] = groups[group] || [];
groups[group].push(arrayRecord);
}
return Object.keys(groups).map((group) => {
return groups[group];
});
}
const arr = [
{name: '王二', age: 18, role: '销售'},
{name: '张三', age: 20, role: '店长'},
{name: '李四', age: 18, role: '经理'},
{name: '许五', age: 20, role: '店长'},
{name: '许溜', age: 24, role: '店长'},
{name: '六六', age: 24, role: '销售'},
{name: '七七', age: 23, role: '销售'},
{name: '八八', age: 24, role: '销售'},
{name: '九九', age: 23, role: '销售'},
];
const result = arrayGroup(arr, ['role', 'age']);