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

如何按对象中指定数组排序并保持其余关联数组元素的相对位置

实现方案

不用硬转二维数组再拆分,用「排序索引映射」的方式写起来更简洁,适配性也更高:

核心思路

先基于bar数组的值生成排序后的索引序列,再用这个索引序列批量重组所有关联数组即可。

代码实现

let obj = {
    "foo": ["orange", "apple", "pear", "grape", "lime"],
    "bar": [12, 6, 18, 3, 22],
    "bat": ["a", "b", "c", "d", "e"]
};

// 1. 生成按bar数值升序排列的索引数组
const sortedIndices = Array.from(obj.bar.keys())
    .sort((a, b) => obj.bar[a] - obj.bar[b]);

// 2. 批量更新所有数组(修改原对象)
Object.keys(obj).forEach(key => {
    obj[key] = sortedIndices.map(idx => obj[key][idx]);
});

如果不想修改原对象,可以生成新对象:

const sortedObj = Object.fromEntries(
    Object.entries(obj).map(([key, arr]) => [
        key,
        sortedIndices.map(idx => arr[idx])
    ])
);

效果验证

执行后obj的输出完全符合预期:

{
  foo: ['grape', 'apple', 'orange', 'pear', 'lime'],
  bar: [3, 6, 12, 18, 22],
  bat: ['d', 'b', 'a', 'c', 'e']
}

这种写法的优势是后续如果给对象新增其他同长度的关联数组,不需要修改逻辑就能自动适配排序。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 17:36:04