有没有一种方法可以使选定的标签组合以仅显示与所有标签匹配的项目? [英] Is there a way to have selected tags combine to show only items matching all tags?

查看:50
本文介绍了有没有一种方法可以使选定的标签组合以仅显示与所有标签匹配的项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究一个简单的会议列表,在React中显示,搜索和过滤应用程序.

I'm working on a simple meeting listing display, search, and filter application in React.

设置代码以过滤带有各种标签"的结果(从Google表格中提取).但是,每个附加标签都充当联合,而不是添加更多条目而不是减少条目的交集.

The code is set up to filter the results (pulled from a Google Sheet) with various "tags". Each additional tag, however, works as a union, not an intersection adding more entries instead of whittling them down.

  //filter meetings based on selected tags
  if (tags.length) {
    meetings = meetings.filter(meeting => {
      for (let i = 0; i < tags.length; i++) {
        if (meeting.tags.includes(tags[i])) return true;
        console.log(tags[i])
      }
      return false;
    });
  }

我一直在寻找一种方法来将包含"功能换成某种要求所有选定标签都出现在条目中才能显示的东西.

I was looking for some way to swap out the "includes" function for something that requires all the selected tags to be present in the entry for it to show.

完整代码可在此处查看: https://github.com/abhinemani/oiaa

The full code can be seen here: https://github.com/abhinemani/oiaa

推荐答案

Array.prototype.every()测试数组中的所有元素是否都通过谓词.

Array.prototype.every() tests whether all elements in array pass the predicate.

请注意,对于空数组, Array.prototype.every()返回true,因此您可能还需要添加对会议标签长度的检查:

Note that Array.prototype.every() returns true for empty arrays, so you may want to add a check for meeting tags length too:

var tags = [1,2,3];
var meetings = [{ id: 0, tags: [1,2]}, {id: 1, tags: [1,2,3]}, {id: 2, tags:[1]}, {id: 3, tags: []}, {id: 4, tags: [1,2,3] }];

meetings = meetings.filter(meeting =>
	!tags.length || tags.every((tag) =>
  	     meeting.tags && meeting.tags.length && meeting.tags.includes(tag)
        )
);

console.log(meetings);

这篇关于有没有一种方法可以使选定的标签组合以仅显示与所有标签匹配的项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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