gpt4 book ai didi

javascript - 如何通过相同键的属性重新排列嵌套数组

转载 作者:行者123 更新时间:2023-12-02 14:59:27 25 4
gpt4 key购买 nike

D3.JS 或 javascript/jquery 有没有办法做到这一点:

我有一个数组数组..

[
[{date:x,data:1},{date:y,data:5},{date:z,data:2}],
[{date:x,data:9},{date:y,data:10}],
[{date:y,data:8},{date:z,data:5}]
]

我想重新排列它们,以便该顶级数组中的数组都具有相同的日期:

[
[{date:x,data:1},{date:x,data:9}],
[{date:y,data:5},{date:y,data:10},{date:y,data:8}],
[{date:z,data:2},{date:z,data:5}]
]

最佳答案

使用 d3 非常简单:

xs = [
[{date: 'x', data: 1}, {date: 'y', data: 5}, {date: 'z', data: 2}],
[{date: 'x', data: 9}, {date: 'y', data: 10}],
[{date: 'y', data: 8}, {date: 'z', data: 5}]
]

z = d3.nest()
.key(x => x.date)
.sortKeys(d3.ascending)
.entries(d3.merge(xs))
.map(x => x.values)


z.map(e => document.write('<pre>'+JSON.stringify(e)+'</pre>'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>

关于javascript - 如何通过相同键的属性重新排列嵌套数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35542212/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com