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 []
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)); // []
arr.filter()檢測數值元素,並返回符合條件全部元素的數組。javascript
arr.join()把數組的全部元素放入一個字符串java
arr.indexOf()搜索數組中的元素,並返回它所在的位置。數組
function inArray(array1,array2){ return array1.filter(function(value){return (array2.join('-').indexOf(value))!=-1}).sort(); }