通过与另一个数组的值比较对数组进行排序 [英] Sort an array by comparison with values of another array

查看:81
本文介绍了通过与另一个数组的值比较对数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个数组:

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'] },
];

推荐答案

您可以使用

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

如果ab都具有匹配的标签或没有标签,则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屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆