Javascript按多个字符串过滤数组

时间:2014-09-25 13:10:07

标签: javascript arrays search for-loop keyword

你好

我试图过滤名为 products 的数组,每个产品填充1个字符串。

var products = [
    'canadian black angus beef fresh',
    'canadian black angus beef frozen',
    'american black angus beef frozen'
];

搜索首先将表单输入elemnt拆分为名为 keywords 的数组中的空格,其中包含可变长度的字符串。

var keywords = ['angus', 'fresh'];

实际上我正在循环使用product_array并为keyword_array创建第二个(内部)for循环。直到现在一切都很好。

这是我的缩短代码,显示了这个问题:

function test() {

    var products = [
        'canadian black angus beef fresh',
        'canadian black angus beef frozen',
        'american black angus beef frozen'
    ];

    var keywords = ['angus', 'fresh'];
    var hits = [];

    for (var i = 0; i < products.length; i++) {

        for (var j = 0; j < keywords.length; j++) {

            if (products[i].indexOf(keywords[j]) != -1) {

                /*
                a if case for looped '&&' operator 
                would be great - or something like that
                looped because of the variable length of keywords
                */
                hits.push(products[i]);

            }

        }

    }

    console.log(hits);
    /* 
    all products :/ - because all product matches with 'angus'
    but im searching for an product that contains 'angus' && 'fresh'
    */

}

一些想法?!

4 个答案:

答案 0 :(得分:1)

只需输入一个标记,检查是否包含所有关键字:

var containsAll;

for (var i = 0; i < products.length; i++) {

    // Initialize flag -> guess that this product is correct
    containsAll = true;
    for (var j = 0; j < keywords.length; j++) {
        if (products[i].indexOf(keywords[j]) === -1) {
            // This keyword is not matched -> incorrect product
            containsAll = false;
            break;
        }
    }

    // All products has been matched
    if (containsAll) hits.push(products[i]);
}

看到这个小提琴:http://jsfiddle.net/eoz1y8n4/

答案 1 :(得分:1)

首先,您应该看一下.filter()函数。它遍历一个数组,并根据您设置的条件的真/假返回值返回您​​想要的项目。

MDN's Docs on Array.prototype.filter()

现在,为了确保两个关键字都存在,您可以使用一些标志来指示它是否存在:

var hits = products.filter(function(item) {
    var valid = true;
    for (var i = 0; i < keywords.length; i++) {
        if (item.indexOf(keywords[i]) === -1) {
            valid = false;
        }
    }

    return valid;
});

答案 2 :(得分:0)

您只需要确保您的产品中包含所有关键字:

function test() {

    var products = [
        'canadian black angus beef fresh',
        'canadian black angus beef frozen',
        'american black angus beef frozen'];

    var keywords = ['angus', 'fresh'];
    var hits = [];

    for (var i = 0; i < products.length; i++) {
        var allKeywordsMatch = true;
        for (var j = 0; j < keywords.length; j++) {

            if (products[i].indexOf(keywords[j]) === -1) {

                allKeywordsMatch = false;
                break;
            }

        }

        if (allKeywordsMatch) hits.push(products[i]);

    }

    alert(hits);
}


test();

答案 3 :(得分:0)

该线程帮助我在搜索中获得了理想的结果,在此基础上,我扩展了上面给出的解决方案,可以在对象数组和多个字段(如标题,类别或标签)中进行搜索。

  

我将用代码发布答案,以在任何开发人员在这种情况下需要此帮助时提供帮助。仍有机会进一步改进,我希望这对某人有所帮助。

我的要求是:

  • 要查找标题(字符串),类别(字符串)或标签数组(字符串数组)中的搜索词。
  • 搜索词可以是多个,且用空格分隔。 “ Es6 IIFE”
  • 搜索词可以按任意顺序出现在字符串中的任意位置

我已经准备了一个实时演示。您可以运行并检查结果。

我有以下对象数组示例,其中包含文章列表

let articles = [
            { "title": "ES6 — set, map, weak", "category": "ES6", "tags": ["ES6", "Set", "Map", "Weak"] },
            { "title": "JavaScript Modules: From IIFEs to CommonJS to ES6 Modules", "category": "JavaScript", "tags": ["JavaScript", "Modules", "IIFE", "ES6 Modules"] },
            { "title": "A guide to JavaScript Regular Expressions", "category": "JavaScript", "tags": ["JavaScript", "RegExp", "Regular Expressions"] },
        ];

如果有人在“搜索”框中键入“ es6 iife”,然后按一下按钮,则它将首先查看“标签”数组,如果找不到,则将查看“标题”和“类别”。

let output = document.querySelector('#output');
let articles = [
	{ "title": "ES6 — set, map, weak", "category": "ES6", "tags": ["ES6", "Set", "Map", "Weak"] },
	{ "title": "JavaScript Modules: From IIFEs to CommonJS to ES6 Modules", "category": "JavaScript", "tags": ["JavaScript", "Modules", "IIFE", "ES6 Modules"] },
	{ "title": "A guide to JavaScript Regular Expressions", "category": "JavaScript", "tags": ["JavaScript", "RegExp", "Regular Expressions"] },
];

let initialContent = '';
articles.map(article => {
	initialContent += `<li>
		<p><b>Title : </b> ${article.title}</p>
		<p><b>Category : </b> ${article.category}</p>
		<p><b>Tags : </b> ${article.tags}</p>
		</li>`;
});

output.innerHTML = initialContent;

function filter() {
	let searchTerm = document.querySelector('#searchBox').value;
	let keywords = searchTerm.split(' ');
	let articleBySearch = [];

	articles.map((article) => {
		let allKeywordsMatch = true;

		keywords.map((keyword) => {
			if (article.tags.some((tag) => tag.toLowerCase().indexOf(keyword.toLowerCase()) !== -1)) {
				allKeywordsMatch = true;
			} else {
				if (article.title.toLowerCase().indexOf(keyword.toLowerCase()) === -1 && article.category.toLowerCase().indexOf(keyword.toLowerCase()) === -1) {
					allKeywordsMatch = false;
				}
			}
		});

		if (allKeywordsMatch) articleBySearch.push(article);
	});

	// Display Output in the browser
	let htmlContent = '';
	articleBySearch.map(article => {
		htmlContent += `<li>
		<p><b>Title : </b> ${article.title}</p>
		<p><b>Category : </b> ${article.category}</p>
		<p><b>Tags : </b> ${article.tags}</p>
		</li>`;
	});

	output.innerHTML = htmlContent;
}
body {
	font-family: Arial, Helvetica, sans-serif;
	font-size: 16px;
}

.example {
	border: 1px solid rgb(245, 28, 118);
	width: 400px;
	margin: 0 auto;
	padding: 1em;
}

.example #searchBox {
	padding: 10px;
	border: 1px solid #cccccc;
}

.example #searchBox:focus {
	padding: 10px;
	border: 1px solid #0059ff;
}

.example button {
	padding: 10px;
	color: #FFF;
	background-color: #0059ff;
	border: 1px solid #0059ff;
}

.example ul {
	margin: 0;
	padding: 0;
	list-style: none;
}

.example li {
	border: 1px solid #cccccc;
	padding: 1em;
	margin: 1em 0;
}
<div class="example">
		<input type="text" id="searchBox" placeholder="Type your words to search" />
		<button onClick="filter()">Click to Filter</button>
		<ul id="output"></ul>
</div>