我有一个对象数组,例如:
const arr = [
{
type: 2,
name: 'A',
},
{
type: 1,
name: 'B'},
{
type: 2,
name: 'C'},
{
type: 1,
name: 'D',
},
];
现在您看不到的是,有成对的物体。因此,“ A”和“ B”属于同一类。现在,我想对这个数组进行排序,所以最终它变成了:
const result = [
{
type: 1,
name: 'B',
},
{
type: 2,
name: 'A'},
{
type: 1,
name: 'D'},
{
type: 2,
name: 'C',
},
];
所以基本上我只想对配对进行排序。
我尝试使用here这样的索引
基本上,仅对当前值的索引使用取模运算符,但是我担心排序机制的工作方式会有所不同。
答案 0 :(得分:1)
通过成对,您可以拼接已连接的项目,进行排序并将它们拼接回数组。
var array = [{ type: 2, name: 'A' }, { type: 1, name: 'B' }, { type: 2, name: 'C' }, { type: 1, name: 'D' }],
size = 2,
i = 0;
while (i < array.length) {
array.splice(i, 0, array.splice(i, size).sort((a, b) => a.type - b.type));
i += size;
}
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }
答案 1 :(得分:0)
我假设arePair(a,b)
是包含有关对象对的信息的函数,并且如果参数是成对的,则返回true(我们在编写问题时不知道该信息,但在摘录中我举了一些例子)。我还假设您要按type
arr.sort((a,b) => arePair(a,b) ? a.type-b.type : 0 );
const arr = [
{
type: 2,
name: 'A',
},
{
type: 1,
name: 'B'},
{
type: 2,
name: 'C'},
{
type: 1,
name: 'D',
},
];
const arePair = (a,b) => [ {'A':1,'B':1}, {'C':1,'D':1} ].some(x=> x[a.name]&&x[b.name]);
arr.sort((a,b) => arePair(a,b) ? a.type-b.type : 0 );
console.log(arr);
答案 2 :(得分:0)
我对您的问题的解释是,您的数组是元素对的扁平列表,并且您希望每个对都按type
进行排序。为此,我将介绍一个chunk()
操作和一个flatten()
操作。
chunk(arr, chunksise)
函数采用数组arr
并将其拆分为长度为chunkSize
的块,因此chunk([1,2,3,4,5,6], 3)
为[[1,2,3],[4,5,6]]
。它可以用多种方式编写;这是一个:
const chunk = <T>(arr: T[], chunksize: number) =>
arr.reduce<T[][]>(
(acc, cur) => (
acc[acc.length - 1].length < chunksize || acc.push([]),
acc[acc.length - 1].push(cur),
acc
),
[[]]
);
然后flatten(arr)
接受数组arr
的数组,并将所有数组连接在一起。因此flatten([[1,2,3],[4,5,6]])
是[1,2,3,4,5,6]
。此功能在ESNext中以Array.prorotype.flat()
的形式存在,但我不打算假设您在运行时中具有该方法。可以用多种方式来写。这是一个:
const flatten = <T>(arr: T[][]) =>
arr.reduce<T[]>((acc, cur) => (acc.push(...cur), acc), []);
最后,对于您要执行的操作,我们将采用arr
,将其分成几对,按元素的type
属性对每一对进行排序,然后将结果展平:
const result = flatten(chunk(arr, 2).map(e => e.sort((a, b) => a.type - b.type)));
让我们确保它是您想要的:
console.log(JSON.stringify(result));
// [{"type":1,"name":"B"},{"type":2,"name":"A"},
// {"type":1,"name":"D"},{"type":2,"name":"C"}]
看起来不错。希望能有所帮助;祝你好运!