JavaScript数组查找是否包含某些字符串

Given two arrays of strings a1 and a2 return a sorted array r in lexicographical order of the strings of a1 which are substrings of strings of a2.
Example 1: a1 = ["arp", "live", "strong"]
a2 = ["lively", "alive", "harp", "sharp", "armstrong"]
returns ["arp", "live", "strong"]

Example 2: a1 = ["tarp", "mice", "bull"]
a2 = ["lively", "alive", "harp", "sharp", "armstrong"]
returns []
my answer:
function inArray(array1,array2){
    var array3 = [];
   for(var i = 0 ; i <array1.length ; i++){
     var pattern = RegExp(array1[i]);
     if(pattern.test(array2) ==true && array1[i]!==undefined)
        array3.push(array1[i])
   }
   return array3.sort();
}
测试用
var a2 = ["lively", "alive", "harp", "sharp", "armstrong"]
var a1 = ["xyz", "live", "strong"]
console.log(inArray(a1, a2));   
//["live", "strong"])

var a1 = ["live", "strong", "arp"]
console.log(inArray(a1, a2));    
//["arp", "live", "strong"])

var a1 = ["tarp", "mice", "bull"]
console.log(inArray(a1, a2));   
// []
best answer:

arr.filter()检测数值元素,并返回符合条件所有元素的数组。

arr.join()把数组的所有元素放入一个字符串

arr.indexOf()搜索数组中的元素,并返回它所在的位置。

function inArray(array1,array2){
    return array1.filter(function(value){return (array2.join('-').indexOf(value))!=-1}).sort();
}

转载于:https://www.cnblogs.com/kid2333/p/7439719.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值