d3.js Javascript:sort通过外部map(或外部K.V对)排序对象数组

u5i3ibmn  于 2023-05-07  发布在  Java
关注(0)|答案(1)|浏览(145)

这里的JavaScript新手。I这种类型的问题似乎很常见,我保证我环顾了一段时间,虽然我可能错过了一些东西。
我正试图在一个单独的数据结构(k,v对的Map或对象)中按值对一个对象数组进行排序
要排序的数据(这是Object.fromEntries(d3.rollup( ... ))的结果,用于获取“foo”、“bar”等的出现次数):

dataSortBy = {bar:2, foo:3}

或者,如果更合适,排序依据的值也可以在map中(d3.rollup( ... )的结果):

dataSortByMap =  {foo => 3, bar => 2}

待排序数据:

dataRaw = 
[
{name:"foo", relation:"baz"}
{name:"foo", relation:"buz"}
{name:"bar", relation:"baz"}
{name:"bar", relation:"buz"}
{name:"foo", relation:"biz"}
]

寻找结果:

dataSorted = 
[
{name:"foo", relation:"baz"}
{name:"foo", relation:"buz"}
{name:"foo", relation:"biz"}
{name:"bar", relation:"baz"}
{name:"bar", relation:"buz"}
]

到目前为止,我的方法是遵循https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort#sorting_with_map
感谢您的任何和所有帮助。:)

xriantvc

xriantvc1#

只需在.sort()回调函数中使用sortBy数组:

const dataRaw = 
[
{name:"foo", relation:"baz"},
{name:"foo", relation:"buz"},
{name:"bar", relation:"baz"},
{name:"bar", relation:"buz"},
{name:"foo", relation:"biz"}
], sortBy= {foo:3,bar:2};

console.log(dataRaw.sort((a,b)=>
 sortBy[a.name]-sortBy[b.name]))

相关问题