How to use Builtin Functions ‘every‘, ‘reduce‘, and ‘split‘ In Javascript
- In this apporach we are using inbuilt fucntions rather than using complex data structures.
- We firslty split the input string into words and then by using reduce funtion we create a mapping between pattern chatacters and the corresposnding words.
- Lastly, we check if all the mapped values are aligned properly witht he words in the input string using the every function.
- If they are aligned properly then true result will be returned else false result will be returned.
Example:
function checkPattern(str, pattern) {
let words = str.split(" ");
if (words.length !== pattern.length) {
return false;
}
let patternToWord = pattern.split("").reduce((map, character, index) => {
if (!map.has(character)) {
map.set(character, words[index]);
} else if (map.get(character) !== words[index]) {
return false;
}
return map;
}, new Map());
let values = [...patternToWord.values()];
let ans = values.every((value, index) => value === words[index]);
return ans;
}
console.log(checkPattern("engineers rock", "er"));
console.log(checkPattern("engineers rock", "egr"));
console.log(checkPattern("engineers rock", "gsr"));
Output
true false false
JavaScript Program to Check if String Follows Order of Characters Defined by a Pattern or Not
In this JavaScript article, we will see the solution to the problem of checking if a string follows the order of characters defined by a pattern or not. We have given a string and pattern as the input and our task is to develop a program that will check whether the input string follows the same pattern according to the pattern given.
Example:
To solve this problem, we have three different approaches which are mentioned below:
Table of Content
- Using JavaScript Loops
- Using JavaScript Map
- Using Builtin Functions ‘every’, ‘reduce’, and ‘split’
- Using Regular Expression: