[英]What is the most efficient way to populate an array based on other information in Javascript?
[英]Most efficient way to check array based on other array limitation
我有以下一组数组,我想通过以下数组must_inculde, optional_include, must_not_include
检查哪个数组满足条件
must_inculde
的字母。must_not_include
。optional_include
的值可以是must_inculde
但它们不是必须的。 my_arr = [['a', 'c', 'd', 'b', 'e'],
['a', 'e'],
['a', 'c', 'f'],
['a', 'c', 'b'],
['a', 'b', 'd'],
['a', 'b', 'd', 'c']]
must_inculde = ['a', 'b']
optional_include = ['c', 'd']
must_not_include = ['f']
可选项并不有趣,因为数组永远不会因为这条信息而失败:如果它没有所有这些元素,那就没问题,如果有,也没关系。
所以你只需要检查includes和not-includes,为此你可以使用every
和includes
数组方法:
let my_arr = [['a', 'c', 'd', 'b', 'e'], ['a', 'e'], ['a', 'c', 'f'], ['a', 'c', 'b'], ['a', 'b', 'd'], ['a', 'b', 'd', 'c']] let must_include = ['a', 'b'] let optional_include = ['c', 'd'] let must_not_include = ['f'] let result = my_arr.filter(arr => must_include.every(val => arr.includes(val)) && must_not_include.every(val => !arr.includes(val)) ); console.log(result);
这将为您提供一个带有true
或false
的镜像数组,用于“语句”:
var my_arr = [['a', 'c', 'd', 'b', 'e'], ['a', 'e'], ['a', 'c', 'f'], ['a', 'c', 'b'], ['a', 'b', 'd'], ['a', 'b', 'd', 'c']]; var must_inculde = ['a', 'b']; var optional_include = ['c', 'd']; var must_not_include = ['f']; var mirror=my_arr.map(item=>({ must_inculde:must_inculde.reduce((acc,element)=>{acc=acc&&item.includes(element);return acc;},true), optional_include:item.some(element=>optional_include.includes(element)), must_not_include:!item.some(element=>must_not_include.includes(element)) })); console.log(mirror);
.as-console-wrapper { max-height: 100% !important; top: 0; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.