const arr = [ { name: 'apple', shouzimu: 'a' }, { name: 'banana', shouzimu: 'b' }, { name: 'avocado', shouzimu: 'a' }, { name: 'blueberry', shouzimu: 'b' }, { name: 'cherry', shouzimu: 'c' }, { name: 'coconut', shouzimu: 'c' } ]; const result = arr.reduce((acc, curr) => { const firstLetter = curr.shouzimu.toLowerCase(); // 获取对象中 shouzimu 的首字母并转为小写 if (!acc[firstLetter]) { acc[firstLetter] = []; // 如果新数组中没有这个首字母的键,则创建一个空数组 } acc[firstLetter].push(curr); // 将当前对象添加到对应首字母的数组中 return acc; }, {}); const newArray = Object.values(result); // 提取新数组中的值 console.log(newArray); new Array能不能按照 abcdefghijklmnopqrstuvwxyz 的循序 放进去 使用js 的写法
时间: 2024-04-15 09:27:50 浏览: 19
JavaScript 中的普通数组(`new Array()`)是按照元素插入的顺序进行存储的,因此可以按照 `abcdefghijklmnopqrstuvwxyz` 的顺序将元素放入数组。
下面是使用 JavaScript 的写法来按照 `abcdefghijklmnopqrstuvwxyz` 的顺序将元素放入数组的示例:
```javascript
const arr = [
{ name: 'apple', shouzimu: 'a' },
{ name: 'banana', shouzimu: 'b' },
{ name: 'avocado', shouzimu: 'a' },
{ name: 'blueberry', shouzimu: 'b' },
{ name: 'cherry', shouzimu: 'c' },
{ name: 'coconut', shouzimu: 'c' }
];
const result = arr.reduce((acc, curr) => {
const firstLetter = curr.shouzimu.toLowerCase(); // 获取对象中 shouzimu 的首字母并转为小写
if (!acc[firstLetter]) {
acc[firstLetter] = []; // 如果新数组中没有这个首字母的键,则创建一个空数组
}
acc[firstLetter].push(curr); // 将当前对象添加到对应首字母的数组中
return acc;
}, {});
const newArray = [];
for (let letter of 'abcdefghijklmnopqrstuvwxyz') {
if (result[letter]) {
newArray.push(result[letter]);
}
}
console.log(newArray);
```
这段代码首先使用 `reduce` 方法将原始数组中的对象按照首字母进行分类,并存储在 `result` 对象中。然后,通过一个 `for...of` 循环,按照 `abcdefghijklmnopqrstuvwxyz` 的顺序遍历,并将对应首字母的数组从 `result` 对象中提取出来,并依次放入 `newArray` 数组中。最后,打印输出 `newArray`,即按照 `abcdefghijklmnopqrstuvwxyz` 的顺序存储了各个数组。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)