Home  >  Article  >  Web Front-end  >  Commonly used array string methods

Commonly used array string methods

php中世界最好的语言
php中世界最好的语言Original
2018-03-09 16:11:161612browse

This time I will bring you the commonly used array string method. What are the precautions for using the array string method? The following is a practical case, let’s take a look.

1. Array operation

Array deduplication

Use the uniqueness of the key in the Object to filter

function unique(arr){    var obj = {}    var data = []    for(var i in arr){        if(!obj[arr[i]]){
            obj[arr[i]] = true;
            data.push(arr[i]);
        }
    }    return data;
}

The largest number in the array Difference

function getMaxProfit(arr){    var min = arr[0], max = arr[0];    for(var i=0;imax)
            max = arr[i];
    }    return max - min;
}

2. String operation

Generate a random string of specified length

function randomString(n){    var str = 'abcdefghijklmnopqrstuvwxyz0123456789';    var tmp = '';    for(var i=0;i

Count the most frequent letters in the string (using the uniqueness of the key in the Object , use key to filter, and then count)

function findMaxDuplicateChar(str) {    if(str.length == 1) {        return str;
    }    var charObj = {};    for(var i = 0; i < str.length; i++) {        if(!charObj[str.charAt(i)]) {
            charObj[str.charAt(i)] = 1;
        } else {
            charObj[str.charAt(i)] += 1;
        }
    }    var maxChar = '',
        maxValue = 1;    for(var k in charObj) {        if(charObj[k] >= maxValue) {
            maxChar = k;
            maxValue = charObj[k];
        }
    }    return maxChar + ':' + maxValue;
}

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the PHP Chinese website!

Related reading:

How to filter out false, null, 0, "", undefined, and NaN values ​​in a js array

How to modify the scroll bar style

table tr th and table tr td have too many fonts, how to use CSS to solve it

The above is the detailed content of Commonly used array string methods. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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