我有两个数组:
const tags = ['one', 'two', 'three'];
let posts = [
{ tags: ['four', 'five'] },
{ tags: ['one', 'six'] },
{ tags: ['seven'] },
{ tags: ['nine', 'two'] },
];
我需要以这种方式对 posts
数组进行排序:具有 tags
数组中至少一个标签的元素必须位于数组的开头。其余元素(没有匹配标签)的顺序并不重要。
预期结果:
posts = [
{ tags: ['one', 'six'] },
{ tags: ['nine', 'two'] },
{ tags: ['four', 'five'] },
{ tags: ['seven'] },
];
最佳答案
您可以使用 some
检查 tags
数组中是否存在每个对象的任何标签。和 includes
。然后减去正在比较的 2 个对象的值。
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
具有优先级。
相反的情况,返回1
如果a
和b
都有匹配的标签或没有标签,compareFunction
将返回零。因此,它们相对于彼此没有移动
关于javascript - 通过与另一个数组的值比较来对数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56116034/