Javascript:排序数组对象的外部映射(或外部K.V对)



JavaScript新手。这类问题似乎很常见,我保证我四处看了一会儿,尽管我可能遗漏了一些东西。

我正在尝试按单独数据结构(映射或k,v对的对象)中的值对对象数组进行排序

要排序的数据(这是Object.fromEntries(d3.rollup( ... ))的结果,以获得"foo", "bar"等):

dataSortBy = {bar:2, foo:3}

或者,如果更合适的话,排序的值也可以在map中for (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

感谢所有的帮助。:)

.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]))

相关内容

  • 没有找到相关文章

最新更新