Home > Web Front-end > JS Tutorial > JavaScript fun questions: What's in it?

JavaScript fun questions: What's in it?

黄舟
Release: 2017-02-13 16:02:44
Original
1069 people have browsed it

It is known that there are two string arrays, let’s call them a1, a2.

The current task is to find all elements from a1 that are element substring in a2 and store them in a new array.

Sort this new array in lexicographic order and return it.

Let’s take an example:

a1 = ["arp", "live", "strong"]

a2 = ["lively", "alive" , "harp", "sharp", "armstrong"]


Return["arp", "live", "strong"]

Here, "arp" is a substring of "harp", "live" is a substring of "lively", So it can be returned.

Look at another example:

a1 = ["tarp", "mice", "bull"]

a2 = ["lively", "alive" ", "harp", "sharp", "armstrong"]


Return[]

herea1 None of them conform to the substring rules, so an empty array is returned.

Okay, let’s see how to solve it:

First of all, when I see the substring, I guess I need a way to judge whether it is a substring:


if(typeof String.prototype.isSubstringOf === "undefined"){
    String.prototype.isSubstringOf = function(str){
        return str.indexOf(this) >= 0;
    };
}
Copy after login

Then, go through a1 one by one and determine whether the current element is a substring of the element in a2. If so, push it into the new array.

Then, when the loop ends, the new array is filled.

How to do lexicographic sorting? Do we still need to write algorithms?

It’s not that complicated. JavaScript’s built-in sorting is dictionary order by default.

Then, just sort the new array directly and return it!


function inArray(array1,array2){
    var newArray = [];
    for(var i=0;i<array1.length;i++){
        var temp = array1[i];
        if(temp){
            for(var j=0;j<array2.length;j++){
                if(temp.isSubstringOf(array2[j])){
                    newArray.push(temp);
                    break;
                }
            }
        }
    }
    return newArray.sort();
}
Copy after login


The above is an interesting JavaScript question: What is in it? For more related content, please pay attention to the PHP Chinese website (m.sbmmt.com)!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template