Javascript:将数组中的对象组改组 [英] Javascript: shuffling groups of objects in an array
问题描述
我有一个对象数组,其中已经对一个键(下面的组
)进行了排序,因此所有对象的值都相同组
在数据
的索引中彼此相邻。例如:
I have an array of objects where I have sorted on a key (group
below) such that all of the objects wit hthe same value for group
are adjacent to each other in the indices of data
. For example:
var data = [{foo: "cat", group:"house"},
{foo: "cat", group: "house"},
{foo: "cat", group: "tree"},
{foo: "dog", group: "tree"},
{foo: "dog", group: "car"}];
我正在尝试调整数据中对象的顺序
数组,同时保留键 group
的值内的顺序。换句话说,我试图改组 data
中的对象组,而不是单个对象。虽然我知道如何随机排列数组中的对象,但我不知道如何随机排列数组中的对象组。
I am trying to shuffle the order of the objects in the data
array while preserving the ordering within the values of the key group
. In other words, I am trying to shuffle groups of objects in data
and not the individual objects. While I know how to shuffle objects in an array, I don't know how to shuffle groups of object in an array.
我的想法是,可能有一种方法使用组的值仅在组更改时才更改的事实。
My thoughts were that there might be a way to use the fact that the values of group change only when the group changes.
推荐答案
只需创建一个随机属性即可在组级别,并将属性分配给数组中的每个对象:
Simply create a random property to sort with at the group level and assign the property to each respective object in the array:
var data = [{foo: "cat", group: "house"},
{foo: "cat", group: "house"},
{foo: "cat", group: "tree"},
{foo: "dog", group: "tree"},
{foo: "dog", group: "car"}];
//get random sorting at the group level (via a hashtable)
let randomGroupSortKey = {}
data.forEach(d => randomGroupSortKey[d.group] = Math.random())
console.log("Group sort keys:", randomGroupSortKey)
//add the sortKey property to the individual array entries
let dataSortable = data.map(x => {
return {
...x,
sortKey: randomGroupSortKey[x.group]
}
})
dataSortable.sort((a, b) => a.sortKey - b.sortKey) //sort the groups!
console.log("Result:", dataSortable)
console.log("Result without sortKey:", dataSortable.map(({ sortKey, ...x }) => x))
这篇关于Javascript:将数组中的对象组改组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!