• 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();
    }
    
  • 相关阅读:
    web页面常用方法及INI文件的读取方法
    winform 三个Panel左右切换(panel里面填充图片)
    图片渐出轮播的效果
    Winform跑马灯——Graphics运用
    .net 3.5 新功能重写ToInt()方法
    style.display
    SQL: 分页SQL SQL2005函数分页!
    JS: 验证输入必须为数字
    Table 里面点标题会进行排序
    在Div中绑定数据
  • 原文地址:https://www.cnblogs.com/kid2333/p/7439719.html
Copyright © 2020-2023  润新知