[英]Filter array of objects by array strings and match with substrings of the object
[英]How to filter a large array of strings by an array of substrings?
我正在使用angular來過濾自動完成字段的大量字符串。 什么是最有效的方法?
largeArrayOfStrings = ['string1', 'string2', 'test one', 'one', 'two test', 'three', 'test one two', ...]
substring = [‘test’, ‘one’, ‘two’]
values = substringArray.map(h.includes)
// I would want values to be the following
values = ['test one two']
// That is the only string that contains all the strings from substring array.
將h
變成Set,它具有恆定的查找時間:
const toFilter = new Set(h);
const result = substringArray.filter(el => toFilter.has(el));
這將是一種方法:
const strings = ['string1', 'string2', 'test one', 'one', 'two test', 'three', 'test one two'] const subs = ['test', 'one', 'two'] const result = strings.filter(x => subs.every(y => x.includes(y))) console.log(result)
使用Array.filter
與組合Array.every
和String.includes
。
這個想法是從單詞過濾器開始的,並確保對於subs
數組中的every
子字符串,您都能在main數組的當前單詞中獲得成功。 如圖所示,這僅適用於'test one two'
。
好的,所以我一直在寫一個庫來做這樣的事情,並且我找到了解決這個問題的簡單方法。 該代碼最初是用TypeScript編寫的,但是我已將其轉換為JS:
const filterArray = (arr, toKeep) => {
for (item of toKeep)
arr = arr.filter(i => i = toKeep);
return arr;
};
這意味着該函數假定數組中可以包含字符串以外的其他項,如果要確保字符串,只需在函數的開頭添加以下行即可:
for (arrIetm of arr) if (Object.prototype.toString.call(arrItem) != '[object String]' return;
順便說一句,如果您想檢出庫,則GitHub位於以下鏈接: https : //railrunner16.me/raildash/
祝你好運,祝你好運!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.