【问题标题】:How to add/sum the desired indexs of an array from specific array?如何从特定数组中添加/求和所需的数组索引?
【发布时间】:2021-04-02 19:51:32
【问题描述】:

我有如下数据结构,这个数据需要按照“104”中数组的前两个索引之和排序。

{
  "data":{
    "Org 1":{
      "102":[
        0.1444,
        0.1551,
        0.2369,
        0.3353,
        0.1282
      ],
      "104":[
        0.309,
        0.3483,
        0.218,
        0.0657,
        0.059
      ]
    },
    "Org 2":{
      "102":[
        0.19444444444444448,
        0.1388888888888889,
        0.19444444444444448,
        0.33333333333333326,
        0.1388888888888889
      ],
      "104":[
        0.20588235294117646,
        0.38235294117647056,
        0.14705882352941177,
        0.14705882352941177,
        0.1176470588235294
      ],
    },
    "Org 3":{
      "102":[
        0.0967741935483871,
        0.2903225806451613,
        0.16129032258064516,
        0.3548387096774194,
        0.0967741935483871
      ],
      "104":[
        0.44,
        0.24,
        0.2,
        0.04,
        0.08
      ]
    }
  }
}

我怎样才能做到这一点?有人可以帮忙吗?

这是我迄今为止尝试过的,但没有按预期工作

let orgs = Object.keys(data);
let options = [];
let selection = orgs.forEach((data, d) => {
  data["104"].forEach((val, i) => {
    options[i].data.push(val);
  })
});

【问题讨论】:

  • 你想要的确切输出是什么?
  • 前两个索引总是0和1...
  • 升序还是降序排序?
  • @HereticMonkey 抱歉,我的意思是说数组 104 中前两个索引的值,而不是实际索引。
  • @ZunayedShahriar 按升序排列

标签: javascript arrays ecmascript-6


【解决方案1】:

首先,我们需要将数据转换成一个数组进行排序。

然后定义我们自己的compare函数作为我们的需求。

最后,对数组进行排序。

运行sn-p检查结果。

解决方案:

var data = {
  "Org 1":{
    "102":[
      0.1444,
      0.1551,
      0.2369,
      0.3353,
      0.1282
    ],
    "104":[
      0.309,
      0.3483,
      0.218,
      0.0657,
      0.059
    ]
  },
  "Org 2":{
    "102":[
      0.19444444444444448,
      0.1388888888888889,
      0.19444444444444448,
      0.33333333333333326,
      0.1388888888888889
    ],
    "104":[
      0.20588235294117646,
      0.38235294117647056,
      0.14705882352941177,
      0.14705882352941177,
      0.1176470588235294
    ],
  },
  "Org 3":{
    "102":[
      0.0967741935483871,
      0.2903225806451613,
      0.16129032258064516,
      0.3548387096774194,
      0.0967741935483871
    ],
    "104":[
      0.44,
      0.24,
      0.2,
      0.04,
      0.08
    ]
  }
};

const transformedData = [];

Object.keys(data).forEach(
  f => {
    transformedData.push(data[f]);
  }
)

function compare(a, b) {
  var arrA = a["104"];
  var arrB = b["104"];

  if (arrA[0]+arrA[1] < arrB[0]+arrB[1]) {
    return -1;
  }
  if (arrA[0]+arrA[1] > arrB[0]+arrB[1]) {
    return 1;
  }
  
  return 0;
}

transformedData.sort(compare);
console.log(transformedData);

细分:

(0.205882352941176 + 0.38235294117647) < (0.309 + 0.3483) < (0.44 + 0.24)

【讨论】:

  • 这并没有对结构进行排序,而是将结构更改为可以排序的结构,这不是OP所要求的。
  • @HereticMonkey,我现在很困惑。让我们看看 OP 怎么说。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-03-24
  • 2010-09-25
  • 1970-01-01
  • 2017-11-14
  • 2020-05-02
  • 1970-01-01
  • 2021-11-17
相关资源
最近更新 更多