Home > database >  JavaScript. Count the number of symbols in the given string
JavaScript. Count the number of symbols in the given string

Time:12-29

How would you solve this challenge using only string methods, array methods, and loops?

Count the number of 'xx' in the given string. We'll say that overlapping is allowed, so 'xxx' contains 2 'xx'.

Examples:

countXX('abcxx') → 1
countXX('xxx') → 2
countXX('xxxx') → 3

Thanks!

CodePudding user response:

countX('abcxx') - 1

This would work formal strings, except if they contain a single x.

CodePudding user response:

const input = 'abcxxx';
const asArray = Array.from(input);    // get ["a", "b", "c", "x", "x", "x"]

// Make 2 arrays
const array1 = asArray.slice(1);      // get ["a", "b", "c", "x", "x"]
const array2 = asArray.slice(0, -1);  // get ["b", "c", "x", "x", "x"]

// Combine arrays to get array of pairs
const pairsArray = new Array();
for (let i = 0; i < array1.length && i < array2.length; i  ) {
    pairsArray.push(array1[i]   array2[i]);
}

// Now pairsArray is: ["ab", "bc", "cx", "xx", "xx"]

// Count "xx" in pairs array
const answer = pairsArray.filter(pair => pair === "xx").length;

console.log(answer);

  • Related