Tincdawg
Tincdawg

Reputation: 13

Can't return the length of array when looking for substring

How do I return the length of an array when a substring criterion is met? I have three arrays:

arr1 = ["V1","V1","V1","V1","V1","V2","V2","V2"...]
arr2 = ["A1","A1","B1","B1","B1","A2","A2","A2"...]
arr3 = ["V1A1*","V1A1*","V1B1*","V1B1*"...]

How do I return the length of the filtered arr3, where arr1[i]+arr2[i] is a substring of the element? ("V1A1")

The expected output here would be 2, for the first iteration. (i=0)

Thanks in advance!

Upvotes: 0

Views: 63

Answers (3)

Vivian River
Vivian River

Reputation: 32410

It looks like you're saying that these three arrays are the same length, and for each index i of the array, you want to know if arr1[i] + arr2[i] is a substring of arr3[i]. Then, you want to know how many elements meet this criterea.

To accomplish this, you'll want to look over the indices of the array and use the string.indexOf method to see if your criteria is met.

var length = arr1.length,
    matchCount = 0,
    isMatch, i;

for(i = 0; i < length; i += 1) {
    // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf
    // indexOf returns the array index where the substring is found, or -1 if it is not found
    isMatch = arr3[i].indexOf(arr1[i] + arr2[i]) > -1;
    if (isMatch) {
        matchCount += 1;
    }
}

console.log(matchCount);

Upvotes: 2

jcragun
jcragun

Reputation: 2198

To get the matches and the length of said matches you can use filter. This assumes you want to know the match for each value not an aggregate of the matches.

for (i=0; i < arr1.length-1; i++) {
  const combinedValue = `${arr1[i]}${arr2[i]}`;
  const matches = arr3.filter(e => e.indexOf(combinedValue) > -1);
  console.log(`Number of matches for ${combinedValue}: ${matches.length}`);
}

Upvotes: 0

Code Maniac
Code Maniac

Reputation: 37775

You can use includes and filter.

With includes we check whether arr1[i]+arr2[i] is a sub-string of arr3 or not and based on that we filter.

let arr1 = ["V1","V1","V1","V1","V1","V2","V2","V2"]
let arr2 = ["A1","A1","B1","B1","B1","A2","A2","A2"]
let arr3 = ["V1A1*","V1A1*","V1B1*","V1B1*", 'just for test']

let op = (arr3.filter((e,i)=>e.includes(arr1[i]+arr2[i])) || [] ).length

console.log(op)

Upvotes: 0

Related Questions