Home > Mobile >  Filtering an array of strings based on a character in the string
Filtering an array of strings based on a character in the string

Time:08-09

As a long time dabbler in VBA I'm now having a look at Typescript.

I have an array of strings

Each string is a binary number

I wish to filter the array to obtain all those strings that have a '1' at position X

I can write a normal function to do the job

    function CountOnes( ipArray: string[], ipIndex: number): number
    {
        var myCount:number=0
        for (var ipString of ipArray)
        {
            if (ipString[ipIndex]==="1") { myCount =1}
        }
        return myCount
    }

but I cannot seem to achieve the same using the .filter method (myData is the array of strings, myIndex is the character position)

    myCount = myData.filter((x:string, myIndex:number) => x[myIndex]==="1").length)

What am I not understanding? Please feel free to propose a .reduce method based solution.

Please be aware that from a coding perspective I can achieve the above goal using a filter methodin both VBA and nim (VBA required me to write a FilterIt class) so I'm a bit perplexed as to why I can't achieve my goal in Typescript/javascript.

CodePudding user response:

You're almost there, just a few things: the second argument to the closure you pass to filter is the index of the element x, not the index you want to check for. And second, you've got a stray closing bracket in there.

This would do the trick:

const myIndex = 3;
const myCount = myData.filter((x: string) => x[myIndex]==="1").length;

Note how the closure captures myIndex from the surrounding scope.

Or, using reduce:

const myIndex = 3;
const myCount = myData.reduce((count: number, x: string) => count  = x[myIndex] === "1" ? 1 : 0, 0);

CodePudding user response:

Consider this version:

 function CountOnes( ipArray: string[], ipIndex: number): number
    {
        var myCount:number=0
        for (var ipString of ipArray)
        {
            if (ipString[ipIndex]==="1") { myCount =1}
        }
        return myCount
    }

For the array: ["01000", "00111", "110000"]

In the above code, ipIndex is the one you pass. However, in the filter function

 myCount = myData.filter((x:string, myIndex:number) => x[myIndex]==="1").length)

myIndex is the index of the string x in the array myData. That's why you are getting incorrect output. Try this:

function CountOnes( ipArray: string[], ipIndex: number): number
    {
        return ipArray.filter((x:string) => x[ipIndex]==="1").length)
    }
  • Related