You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用JavaScript按州分组并排序重构locations数组?

解决方案

首先要纠正一个小细节:你给出的目标结构其实是JavaScript对象(不是数组,数组只能用数字作为索引,无法使用TX/MN这类字符串键),以下是实现分组并按州名排序的具体方法:

1. 按州分组

使用Array.reduce()遍历原数组,将同一州的元素归类到对应的键下:

// 按州分组
const grouped = locations.reduce((result, location) => {
  // 如果当前州还没有对应的数组,先初始化
  if (!result[location.state]) {
    result[location.state] = [];
  }
  // 将当前地点对象推入对应州的数组
  result[location.state].push(location);
  return result;
}, {});

2. 按州名字母排序

分组完成后,对州的键按字母顺序排序,确保输出结构有序:

// 获取排序后的州名列表
const sortedStateKeys = Object.keys(grouped).sort();

// 生成有序的分组对象
const sortedGrouped = {};
sortedStateKeys.forEach(state => {
  sortedGrouped[state] = grouped[state];
});

完整可运行代码

整合两步后的完整代码如下:

let locations = [
    { "id": "1", "city": "Kermit", "state": "TX" },
    { "id": "2", "city": "Bloomington", "state": "MN" },
    { "id": "3", "city": "Pauls Valley", "state": "OK" },
    { "id": "4", "city": "Colville", "state": "WA" },
    { "id": "5", "city": "Jacksboro", "state": "TX" },
    { "id": "6", "city": "Shallowater", "state": "TX" }
];

// 分组并按州名排序
const sortedGroupedLocations = Object.keys(
  locations.reduce((acc, loc) => {
    acc[loc.state] = [...(acc[loc.state] || []), loc];
    return acc;
  }, {})
).sort().reduce((acc, state) => {
  acc[state] = acc[state];
  return acc;
}, {});

// 输出结果
console.log(sortedGroupedLocations);

运行这段代码后,你会得到按州名字母顺序排列、同一州城市归为子数组的对象结构,和你需求的目标结构一致。

内容的提问来源于stack exchange,提问作者Akhil

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 18:55:35