javascript - 通过与另一个数组的值比较来对数组进行排序

标签 javascript arrays sorting

我有两个数组:

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

如果ab都有匹配的标签或没有标签,compareFunction将返回零。因此,它们相对于彼此没有移动

关于javascript - 通过与另一个数组的值比较来对数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56116034/

相关文章:

Javascript:按日期字符串属性对对象列表进行排序,其中日期可以是未定义的

javascript - AngularJS - $emit 仅在其当前范围内有效?

java - 使用比较器按字母顺序对对象进行排序?

javascript - 垂直排序对象,对象之间留有边距空间

arrays - 动态填充多维 awk 数组

javascript - 嵌套在 JSON 对象数组中的 JSON 对象数组

javascript - 在javascript中链接多个数组方法

javascript - 使用 Controller 作为语法仅更新范围之一

javascript - 在 map 中心显示信息窗口 - Google 避开高速公路

javascript - 为什么空字符串文字在 javascript 中评估为 false?