I am a beginner in js and trying to solve problems. Suddenly saw a problem but I am confused how can I do it. The problem is
Given a list of names, determine the number of names in that list for which a given query string is a prefix. The prefix must be at least 1 character less than the entire name string.
Example: Names = ['jackson', 'jacques','jack']
query = ['jack']
The complete query string 'jack' is a prefix of jackson but not of jacques or jack. The prefix cannot contain the entire name string, so 'jack' does not qualify.
Input sample:
names = ['steve', 'stevens', 'danny', 'steves', 'dan', 'john', 'johnny', 'joe', 'alex', 'alexander']
query = ['steve','alex','joe', 'john', 'dan']
sample output = [2,1,0,1,1]
Explanation:
Query 1: steve appears as a prefix in two strings: stevens and steves
Query 2: alex appears as a prefix in one string: alexander
Query 3: joe does not appears as a prefix in any string
Query 4: john appears as a prefix in one string: johnny
Query 2: dan appears as a prefix in one string: danny
Code:
/*
* Complete the 'findCompletePrefixes' function below.
*
* The function is expected to return an INTEGER_ARRAY.
* The function accepts the following parameters:
* 1. STRING_ARRAY names
* 2. STRING_ARRAY query
*/
function findCompletePrefixes(names, query) {
// Write your code here
}
CodePudding user response:
const list = ['steve', 'stevens', 'danny', 'steves', 'dan', 'john', 'johnny', 'joe', 'alex', 'alexander']
const query = ['steve','alex','joe', 'john', 'dan']
const calc = (l, q) => q.map( // map over array
e => l.filter(a => a.startsWith(e) && a !== e).length // count occurrence and check if strings are not equal to avoid counting 'steve' as prefixed with 'steve'
);
// sample output = [2,1,0,1,1]
console.log(calc(list, query))
CodePudding user response:
function findCompletePrefixes(names, query) {
return query.map(q => names.filter(f => f.startsWith(q)).length);
}
