如何计算字符串数组中的字符串出现次数?

时间:2018-05-16 12:44:57

标签: javascript arrays string

给定数组:

var arr = [ 'male01', 'woman01', 'male02', 'kid01', 'kid02', 'male06'];

如何计算该数组中male的数量?

预期结果:3

注意:我刚编辑了问题以使其更简单。

4 个答案:

答案 0 :(得分:5)

尝试以下

    #grab the DN of the OU where your computer objects are located...
    $OU = ("OU=Computers,DC=domain,DC=com")

    #put your filtered results in $computers (I filtered for Enabled objects)...
    $computers = @()

    ForEach ($O in $OU) {

        $computers += Get-ADComputer -SearchBase $O -filter 'Enabled -eq "True"' -Properties CN,distinguishedname,lastLogonTimeStamp | Select-Object CN,distinguishedname,lastLogonTimeStamp

    }

    #instantiate some arrays to catch your results
    #collected user info
    $userInfo = @()
    #computers you cannot ping
    $offline = @()
    #computers you can ping but cannot establish WinRM connection
    $winRmIssue = @()

    #iterate over $computers list to get user info on each...
    ForEach ($computer in $computers) {

    #filter out System account SIDs
    $WQLFilter = "NOT SID = 'S-1-5-18' AND NOT SID = 'S-1-5-19' AND NOT SID = 'S-1-5-20'" 

    $WQLFilter = $WQLFilter + " AND NOT SID = `'$FilterSID`'"

    #set number of login events to grab
    $newest = 20     

        #attempt to ping computer once by name. return 'true' is success...
        if (Test-Connection -ComputerName $computer.CN -Count 1 -ErrorAction Stop -Quiet) {

        #if ping is true, try to get some info...
            Try {

        #currently logged in user...
                $user = Get-WmiObject -Class Win32_ComputerSystem -ComputerName $computer.CN | select -ExpandProperty username

        #the most commonly logged in user, based on the past 20 log-ins...
                $UserProperty = @{n="User";e={((New-Object System.Security.Principal.SecurityIdentifier $_.ReplacementStrings[1]).Translate([System.Security.Principal.NTAccount])).ToString()}}
                $logs = Get-EventLog System -Source Microsoft-Windows-Winlogon -ComputerName $computer.CN -newest $newest | select $UserProperty
                $freqent = $logs | Group User | Sort-Object Count | Select -First 1 | Select-Object -ExpandProperty Name

                }

        #catch any connection issues...
            Catch {

                $cantInvoke = [pscustomobject][ordered]@{

                'Computer' = $computer.CN
                'Message' = "Could not Invoke-Command. Probably a WinRM issue."            

                }

                $winRMIssue += $cantInvoke

                }

        #custom psobject of gathered user info...
            $userInfoObj = New-Object psobject -Property ([ordered]@{

                'Computer' = $computer.CN
                'LoggedInUser' = $user
                'mostCommonUser' = $frequent            

                })

                    $userInfo += $userInfoObj

                }

        #if you could not ping the computer, gather that info here in a custom object...               
        else {

             $noPing = [pscustomobject][ordered]@{

             'Computer' = $computer.CN
             'DN' = $computer.distinguishedname
             'lastLogonDate' = [datetime]::FromFileTime($computer.lastLogonTimeStamp).toShortDateString()

             }

             $offline += $noPing

             }

 #then kick out the results to csv
$userInfo | Sort-Object Computer | export-csv -Path c:\path\file.csv -NoTypeInformation

$offline | Sort-Object lastLogonDate | export-csv -Path c:\path.file2csv -NoTypeInformation

$winRmIssue | Sort-Object Computer | export-csv -Path c:\path\file3.csv -NoTypeInformation

答案 1 :(得分:2)

int pos = 0;
String user = "User";
while (input.hasNextLine()) {
    Map<String, String> map = new HashMap<>();
    int loop = 0;
    String[] temp = input.nextLine().split(",");
    for (String temp1 : temp) {
        map.put(headerArray[loop], temp1);
        loop++;
    }
    myMap.put(user + " " + pos, map);
    pos++;
}

答案 2 :(得分:2)

您还可以使用regular expressionsString.prototype.match()

代码:

const arr = ['male01', 'woman01', 'male02', 'kid01', 'kid02', 'male06'];
const count = arr.toString().match(/male/g).length;

console.log(count);

答案 3 :(得分:0)

如果找到的字符串增加了counter的值,则需要迭代到数组的长度。喜欢以下。

var arr = [ 'male01', 'woman01', 'male02', 'kid01', 'kid02', 'male06'];
var stringCount = 0;
for(var i=0;i<arr.length;i++)
{
   if(arr[i].indexOf('male')>-1){
      stringCount++;
   }
}
console.log(stringCount);