在 javascript 中订购字典键是 float

问题描述 投票:0回答:1

我正在尝试使用键、值来订购这个。两者都是浮点数。

{
  '2023.4': '665999.91',
  '2023.5': '1228000.0',
  '2023.6': '643842.86',
  '2023.7': '510166.67',
  '2023.8': '727600.0',
  '2023.9': '535327.63',
  '2024.1': '472591.88',
  '2024.2': '525736.46',
  '2024.3': '596570.0',
  '2024.4': '548539.52',
  '2023.10': '562607.69'
}

我的解决方案不起作用,我在这个问题上碰壁了......

// Convert object to array of objects
const dataArray = Object.entries(trends).map(([key, value]) => ({ [key]: value }));

// Sort the array based on the formatted keys
dataArray.sort((a, b) => {
  const keyA = Object.keys(a)[0];
  const keyB = Object.keys(b)[0];
  const [yearA, monthA] = keyA.split('.').map(part => parseInt(part));
  const [yearB, monthB] = keyB.split('.').map(part => parseInt(part));
  
  if (yearA === yearB) {
    return monthA - monthB;
  } else {
    return yearA - yearB;
  }
});

// Reassign the sorted values back to the original object
dataArray.forEach((item,`your text` index) => {
  const key = Object.keys(item)[0];
  trends[key] = Object.values(item)[0];
});

console.log(data)

订购 javascript 字典 - 数组

javascript arrays dictionary sorting
1个回答
-1
投票

重新分配对象道具时,它们的顺序保持不变,您需要添加它们(到新对象):

const input = {
  '2023.4': '665999.91',
  '2023.5': '1228000.0',
  '2023.6': '643842.86',
  '2023.7': '510166.67',
  '2023.8': '727600.0',
  '2023.9': '535327.63',
  '2024.1': '472591.88',
  '2024.2': '525736.46',
  '2024.3': '596570.0',
  '2024.4': '548539.52',
  '2023.10': '562607.69'
}

const transformKey = key => key.replace(/\.(\d)$/, '.0$1');

const result = Object.keys(input)
  .sort((a, b) => (a = transformKey(a), b = transformKey(b), a > b ? 1 : a < b ? -1 : 0))
  .reduce((r, key) => (r[key] = input[key], r), {});

// if you need to mutate the original object:
Object.getOwnPropertyNames(input).forEach(name => delete input[name]);
Object.assign(input, result);

console.log(input);

但是使用对象来存储有序数据并不是一个好主意。最讨厌我的观点是不能在对象上使用数组方法

© www.soinside.com 2019 - 2024. All rights reserved.