快速创建并填充数组

1
2
3
4
5
const array = new Array(12).fill(0);
console.log(array); // 输出: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

const array = Array.from({ length: 12 }, () => 0);
console.log(array); // 输出: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

数组排序

1
2
3
4
5
6
7
8
const array = [
{ name: 'Alice', value: 30 },
{ name: 'Bob', value: 20 },
{ name: 'Charlie', value: 25 }
];

// 按照 value 属性从大到小排序(改变原数据)
array.sort((a, b) => b.value - a.value);

数组对象分类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
const people = [
{ name: 'tom', age: 17, birthYear: 2021 },
{ name: 'tony', age: 21, birthYear: 2021 },
{ name: 'bob', age: 18, birthYear: 2020 },
{ name: 'bob', age: 18, birthYear: 2021 },
{ name: 'bob', age: 18, birthYear: 2019 },
];

function groupBy(arr, property) {
if (!Array.isArray(arr)) return [];
return arr.reduce((pre, obj) => {
const newObj = {
[property]: obj[property],
data: [obj],
};
if (!pre.length) {
return [newObj];
}
for (let i = 0; i < pre.length; i++) {
let item = pre[i];
if (item[property] === obj[property]) {
item.data = [...item.data, obj];
return pre;
}
}
return [...pre, newObj];
}, []);
}

const value = groupBy(people, 'birthYear');

image-20240724113739202