[英]How to efficiently find group strings containing another string in a string array in JavaScript?
For an array like: 对于像这样的数组:
["abc", "bc", "dd", "d", "ee", "ff", "e"]
What would be an efficient way to get: 一种有效的获取方式:
[["abc", "bc"],["dd", "d"],["ee", "e"]]
Explanation 说明
["abc", "bc"] because "abc" contains "bc"
["dd", "d"] because "dd" contains "d"
["ee", "e"] because "ee" contains "e"
Any new method including parallelism is also welcomed. 也欢迎任何新方法,包括并行性。
You can do it using reduce()
. 您可以使用reduce()
做到这一点。 Check if the element is included by other element. 检查该元素是否包含在其他元素中。 If not then add it as key of accumulator. 如果不是,则将其添加为累加器密钥。 If its included then add it to that array. 如果包含它,则将其添加到该数组。 At last use Object.values()
to get values(arrays). 最后使用Object.values()
来获取值(数组)。 Use filter()
to remove arrays having length = 1
使用filter()
删除length = 1
数组
let arr = ["abc", "bc", "dd", "d", "ee", "ff", "e"] let res = Object.values(arr.reduce((ac,a,i) => { if(!arr.some((x,b) => x.includes(a) && i !== b)) ac[a] = [a]; else { for(let k in ac){ if(k.includes(a)){ ac[k].push(a) break; } } } return ac; },{})).filter(x => x.length -1) console.log(res)
You can loop in reverse direction and using the function splice
you can drop the element and push it into the current array. 您可以反向循环,并使用函数splice
可以放置元素并将其推入当前数组。
let arr = ["abc", "bc", "dd", "d", "ee", "ff", "e"]; let result = []; for (let i = arr.length - 1; i >= 0; i--) { let target = arr.splice(i, 1).pop(); if (target === undefined) continue; let current = [target], index = 0; while ((index = arr.findIndex(s => s.includes(target))) != -1) { current.push(arr[index]); arr.splice(index, 1); } if (current.length > 1) result.push(current); } console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.