通过与另一个数组的值比较对数组进行排序 [英] Sort an array by comparison with values of another array
问题描述
我有两个数组:
const tags = ['one', 'two', 'three'];
let posts = [
{ tags: ['four', 'five'] },
{ tags: ['one', 'six'] },
{ tags: ['seven'] },
{ tags: ['nine', 'two'] },
];
我需要以这种方式对posts
数组进行排序:从tags
数组中至少带有一个标签的元素必须位于数组的开头.其余元素(没有匹配标签)的顺序并不重要.
I need to sort posts
array in this way: elements with at least one tag from tags
array must be at the beginning of the array. The order of the remaining elements (without matching tags) is not important.
预期结果:
posts = [
{ tags: ['one', 'six'] },
{ tags: ['nine', 'two'] },
{ tags: ['four', 'five'] },
{ tags: ['seven'] },
];
推荐答案
您可以使用 includes
.然后减去要比较的2个对象的值.
You could check if any of the tags of each object exists in tags
array using some
and includes
. Then subtract the value for 2 objects being compared.
const tags = ['one', 'two', 'three'];
let posts = [
{ tags: ['four', 'five'] },
{ tags: ['one', 'six'] },
{ tags: ['seven'] },
{ tags: ['nine', 'two'] },
];
posts.sort((a, b) =>
tags.some(t => b.tags.includes(t)) - tags.some(t => a.tags.includes(t))
)
console.log(posts)
如果a
具有匹配的标签,而b
没有,则compareFunction
返回-1(false - true
),并且a
相对于b
优先.
If a
has a matching tag and b
doesn't, then the compareFunction
returns -1 (false - true
) and a
is prioritized relative to b
.
在相反的情况下,它返回1
For the reverse situation, it returns 1
如果a
和b
都具有匹配的标签或没有标签,则compareFunction
将返回零.因此,它们彼此之间相对不动
If both of a
and b
have a matching tag or don't have a tag, compareFunction
will return zero. So, they are unmoved relative to each other
这篇关于通过与另一个数组的值比较对数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!