Creating an if-statement without hard-coding - javascript

I have an array that I want to check, for example:
var str = ["a","b","c","d","e","f"];
but I want check if this array's string values are in a database or of some sort. I want to find out which one matches and store the found matches inside an array.
var dataFound = [];
var count = 0;
for(var stringData in someDatabase){
if(stringData == str[0] || stringData == str[1] ...etc){
dataFound[count] = stringData;
count++;
}
}
//someDatabase will consist of strings like random alphabets
from a-z
I don't want to hardcode the if-statement because a query array can be anywhere from a, b, c .. (n) as n can represent any amount of strings. I tried to use a for-loop from 0 to str.length but that can take quite a while when I can use or operator to search in one go with all the string values, is there a way around this?

if (str.indexOf(stringData) > -1) {
//found
}
Array.prototype.indexOf() (MDN)

If str is an array, can you do this?
var dataFound = [];
var count = 0;
for(var stringData in someDatabase){
for (i++; i < str.length; i++) {
if(stringData == str[i]){
dataFound[count] = stringData;
count++;
}
}
}

Related

Javascript: converting string to an array

This is one of my function for a calculator project. First I needed to convert the input string into an array, and do the operation later. (assuming that input has only numbers and '+' sign for now.
My question here is, how do I improve this code? What are the other ways to deal with this problem? (Time complexity, cleanness, shorter code.......whatever)
function convertArray(input) {
let array = [];
let num = "";
for (let i = 0; i < input.length; i++) {
if (input.charAt(i) == '+') {
array.push(input.charAt(i));
} else {
do {
num += input.charAt(i);
i++;
} while (i < input.length && input.charAt(i) !== '+');
array.push(num);
num = "";
i--;
}
}
return array;
}
console.log(convertArray("10+2+3000+70+1"));
You could split with a group. this add the group as well to the array.
For other calculation signs, you could add them to the brackets.
const convertArray = string => string.split(/([+])/);
console.log(convertArray("10+2+3000+70+1"));
const q = prompt('Sum?');
alert('Answer: ' + eval(q));
Would not recommend using eval, but if all you need is a quick and dirty trick, it works.
Personally, I'd recommend a library such as Math.js, but any will do.
If you really need to do this by yourself for a project, I'd recommend checking out the answers here: Evaluating a string as a mathematical expression in JavaScript.
Hope you succeed in whatever you're planning on doing.
It seems the complexity must have something to do with your wish to determing operators. In your code you just push them all into the array. To do that is like
const re = /((\d+)|([^\d]+))/g
const convertArray = str => {
let match, arr=[];
while (match = re.exec(str)) {
arr.push(match[1]) // here you can determine if you have an operator
console.log(match[1],"Operator?",!/^\d+$/.test(match[1]))
}
return arr
}
const str = "10+2+3000+70+1";
console.log(convertArray(str));

Finding a first letter most repeated in an string

Good evening, I proceed to explain my situation. I started to get interested in javascript which started to dabble
in this language, I have been doing some online courses which I have encountered the following task, basically I am trying through the condition "for" tell me what is the first repeated letter of a string also adding the funsion ".UpperCase () "which at the beginning worked best, until I entered more characters to the string in this case" x "throwing me as output result" undefined "instead of" the most repeated word is: X "reach the case that the string should Consider all the letters regardless of whether they are lowercase or capital letters, for which I ask for help to understand if ¿there is another way? for this task and thus move forward (Sorry for my bad english)
Well i making this task in JavasScript with Atom Editor
var word = "SQSQSQSSaaaassssxxxY";
var contendor = [];
var calc = [];
var mycalc = 0;
function repeat() {
for (var i = 0; i < word.length; i++) {
if (contendor.includes(word[i])) {} else {
contendor.push(word[i])
calc.push(0)
}
}
for (var p = 0; p < word.length; p++) {
for (var l = 0; l < contendor.length; l++) {
if (word[p].toUpperCase() == word[l]) {
calc[l] = calc[l] + 1
}
}
}
for (var f = 0; f < calc.length; f++) {
if (calc[f] > mycalc) {
mycalc = calc[f]
}
}
}
repeat()
console.log("The first letter repeated its: " + contendor[mycalc])
I expected the output of the String to be: "X"
but the actual output is: "Undefined"
The first error in your script is that you store the wrong value in mycalc:
mycalc = calc[f]
Since you want mycalc to be an index, the above should have been
mycalc = f
Now, you will get a result, but your code is actually going through a lot of effort to find the uppercase character that is repeated most often, not first.
Your comparison should have used toUpperCase on both sides of the comparison, otherwise lower case letters will never match.
To get the character that was repeated most often, you could use a Map (to keep track of the counts like you did in calc):
function mostRepeated(str) {
const map = new Map;
let result;
let maxCount = 0;
for (let ch of str) {
ch = ch.toUpperCase();
let count = (map.get(ch) || 0) + 1;
map.set(ch, count);
if (count > maxCount) {
maxCount = count;
result = ch;
}
}
return result;
}
var word = "MBXAYMZAXmZYxxxxxxxxxxmBxAYMZaXmZY";
console.log(mostRepeated(word));
Note that you should better use function parameters and local variables. Declaring your variables as global is not considered best practice.
You could find the letter that occurs the most number of times in a string by:
first creating a map that relates each unique letter, to the number of times it occurs in the string
converting that map to an array of "key/value" entries, and then sorting those entries by the "count value"
returning the "letter key" that has the largest count
One way to express this in JavaScript would be via the following:
function findMaxLetter(word) {
/* Create a map that relates letters to the number of times that letter occours */
const letterCounts = Array.from(word).reduce((map, letter) => {
return { ...map, [letter] : (map[letter] === undefined ? 0 : map[letter] + 1) }
}, {})
/* Sort letters by the number of times they occour, as determined in letterCounts map */
const letters = Object.entries(letterCounts).sort(([letter0, count0], [letter1, count1]) => {
return count1 - count0
})
.map(([letter]) => letter)
/* Return letter that occoured the most number of times */
return letters[0]
}
console.log("The first letter repeated its: " + findMaxLetter("MBXAYMZAXmZYxxxxxxxxxxmBxAYMZaXmZY"))
I this is solution is most detailed for you
function func( word ){
word = word.toLowerCase();
var i, charCountCache = {};
//store all char counts into an object
for( i = 0; i < word.length; i++){
if( charCountCache[ word[ i ] ] )
charCountCache[ word[ i ] ] = charCountCache[ word[ i ] ] + 1;
else
charCountCache[ word[ i ] ] = 1;
}
//find the max value of char count in cached object
var fieldNames = Object.keys( charCountCache )
, fieldValues = Object.values( charCountCache )
, mostReapeatChar = '', mostReapeatCharCount = 0;
for( i = 0; i < fieldNames.length; i++ ){
if( mostReapeatCharCount < fieldValues[i] ){
mostReapeatCharCount = fieldValues[i];
mostReapeatChar = fieldNames[i];
}
}
console.log('most repeating char: ', mostReapeatChar, ' no of times: ', mostReapeatCharCount )
}
console.log("The first letter repeated its: " + contendor[mycalc])
You tried to print the 14th index of contendor which has only 9 values, that is why your log result was undefined.
You probably wanted to print word[mycalc].
Also if you intended to count x as X, you should have added toUpperCase() to every letter you process/go-through.
This is only a note to the issues in your code, there are better/faster/cleaner solutions to reach the result which i am sure other answers will provide.
my advice would be to create a hashmap such as
letter => [indexLetter1, indexLetter2].
From that hashmap, you could easily find your first repeated letters.
For that string MBXAYMZAXmZYxxxxxxxxxxmBxAYMZaXmZY, hashmap will look like
[
M => [0,5,..],
B => [1, ..],
X => [2, ..],
...
]
now you can find every letter with multiple values in its array, then in those arrays take the one with the lowest value.
If you want to get the index of most repeated letter, you can use Array.from to convert the word into an array. Add a map function to make all letters uppercase.
Get the count of each letter by using reduce and Object.entries
Use indexOf to the get the index of the lettet in the array. Please note that indexOf count the letters from 0.
var word = "MBXAYMZAXmZYxxxxxxxxxxmBxAYMZaXmZY";
var letters = Array.from(word, o => o.toUpperCase());
var [highestLetter, highestCount]= Object.entries(letters.reduce((c, v) => (c[v] = (c[v] || 0) + 1, c), {})).reduce((c, v) => c[1] > v[1] ? c : v);
var index = letters.indexOf(highestLetter);
console.log("Most repeated letter:", highestLetter);
console.log("Count:", highestCount);
console.log("First Index:", index);

if input string is same as the reversed output string, it should display reversed word

I am trying to check if the input string is the same as the reversed output string, and if so, it should display reversed word.
var word = "cel";
var reverseWord = "lec";
for (i=0; i < word.length; i++) {
for (j=0; j < reverseWord.length; j++) {
if (word[i] === reverseWord[j] && word[i+1] === reverseWord[j+1] && word[i+2] === reverseWord[j+2]) {
console.log("reverseWord----->");
}
}
}
If you want to check if a reversed string is the same as another string, simply use below code
var word = "cel";
var reverseWord = "lec";
console.log(word.split("").reverse().join("") === reverseWord);
Without using the reverse method
var word = "cel";
var reverseWord = "lec";
var arr = [];
for(i=word.length-1;i>=0;i--){
arr.push(word[i]);
}
var new_word = arr.join("");
if(new_word === reverseWord){
console.log("true");
}
else{
console.log("false");
}
So you can use an array to push individual characters of the string into it in reverse order using a loop and convert the array back into a string using join() method and do the check. Hope this helps.

Javascript, Array first letter get from letter to letter

I have an array of names from A-Z in ABC order and I want to get all the names from A to J. Is there any way to do this besides checking the first letter of each character against an array of all the letters from A to J?
Example:
var array=['Amy','Dolly','Jason','Madison','Patricia'];
And I want an array of Amy, Dolly and Jason.
You can use filter function like
var array=['Amy','Dolly','Jason','Madison','Patricia'];
var filtered = array.filter(function(el){return el[0]>='A' && el[0]<='J'})
var array=['Amy','Dolly','Jason','Madison','Patricia'];
var filtered = array.filter(function(el){return el[0]>='A' && el[0]<='J'});
document.getElementById('res').innerHTML = JSON.stringify(array) + '<br />' + JSON.stringify(filtered);
<div id="res"></div>
Code above checking all element in array, if you want avoid it and array already sorted, you can use simple for loop
var array=['Amy','Dolly','Jason','Madison','Patricia'];
var result=[];
for(var i=0;i<len=array.length; i<len && (array[i][0]>='A' && array[i][0]<='J'); i++){
result.push(array[i]);
}
or same in one liner
for(var i=0, result=[], len=array.length; i<len && (array[i][0]>='A' && array[i][0]<='J');result.push(array[i]),i++);
in result - filtered collection;
Yet another way find index and then use slice like
for(var i=0, len=array.length; i<len && (array[i][0]>='A' && array[i][0]<='J');i++);
var result = array.slice(0,i);
Interesing way from #dandavis in comment with filter and regex
var filtered = array.filter(/./.test, /^[A-J]/);
it altervative for
var regex = /^[A-J]/;
var filtered = array.filter(function(el){ return regex.test(el); });
You can do this using regular expression..
var array=['Amy','Dolly','Jason','Madison','Patricia'];
var reg = new RegExp('^[A-J]');
var arrTemp=[];
var intLength = array.length;
for(var i=0;i<intLength ;i++){
if(reg.test(array[i])) {
arrTemp.push(array[i])
}
}
console.log(arrTemp)
If you want consider case-sesitive nature then you can write your regular expression like
var reg = new RegExp('^[A-Ja-j]');
You can use the ascii-value of the character and use a filter to get the result you want. The character code value of "J" is 74 and for "A" it is 65.
array.filter(function(v) { return v.charCodeAt(0) >= 65 && v.charCodeAt(0) <= 74 })
var array = ['Amy', 'Dolly', 'Jason', 'Madison', 'Patricia'],
bound = { lower: 'A', upper: 'J' },
newArray = [],
i = 0, j, l = array.length;
// lookup for the first element of the array which is smaller than the lower bound
while (i < l && array[i][0] < bound.lower) {
i++;
}
j = i;
// lookup for the end of the upper bound and skip the rest
while (j < l && array[j][0] <= bound.upper) {
j++;
}
// build new array
newArray = array.slice(i, j);

Using search method from string

I'm trying to count the number of times certain words appear in the strings. Every time I run it I get a
uncaught TypeErro: undefined is not a function
I just actually need to count the number of times each "major" appears.
Below is my code:
for(var i = 0; i < sortedarray.length; i++)
{
if(sortedarray.search("Multimedia") === true)
{
multimedia += 1;
}
}
console.log(multimedia);
Here is my csv file which is stored in a 1d array.
"NAME","MAJOR","CLASS STANDING","ENROLLMENT STATUS"
"Smith, John A","Computer Science","Senior","E"
"Johnson, Brenda B","Computer Science","Senior","E"
"Green, Daisy L","Information Technology","Senior","E"
"Wilson, Don A","Information Technology","Junior","W"
"Brown, Jack J","Multimedia","Senior","E"
"Schultz, Doug A","Network Administration","Junior","E"
"Webber, Justin","Business Administration","Senior","E"
"Alexander, Debbie B","Multimedia","Senior","E"
"St. John, Susan G","Information Technology","Junior","D"
"Finklestein, Harold W","Multimedia","Freshman","E"
You need to search inside each string not the array. To only search inside the "Major" column, you can start your loop at index 1 and increment by 4 :
var multimedia = 0;
for(var i = 1; i < sortedarray.length; i += 4)
{
if(sortedarray[i].indexOf("Multimedia") > -1)
{
multimedia += 1;
}
}
console.log(multimedia);
What you're probably trying to do is:
for(var i = 0; i < sortedarray.length; i++)
{
if(sortedarray[i].indexOf("Multimedia") !== -1)
{
multimedia++;
}
}
console.log(multimedia);
I use indexOf since search is a bit of overkill if you're not using regexes.
Also, I replaced the += 1 with ++. It's practically the same.
Here's a more straightforward solution. First you count all the words using reduce, then you can access them with dot notation (or bracket notation if you have a string or dynamic value):
var words = ["NAME","MAJOR","CLASS STANDING","ENROLLMENT STATUS"...]
var count = function(xs) {
return xs.reduce(function(acc, x) {
// If a word already appeared, increment count by one
// otherwise initialize count to one
acc[x] = ++acc[x] || 1
return acc
},{}) // an object to accumulate the results
}
var counted = count(words)
// dot notation
counted.Multimedia //=> 3
// bracket notation
counted['Information Technology'] //=> 3
I don't know exactly that you need this or not. But I think its better to count each word occurrences in single loop like this:
var occurencesOfWords = {};
for(var i = 0; i < sortedarray.length; i++)
{
var noOfOccurences = (occurencesOfWords[sortedarray[i]]==undefined?
1 : ++occurencesOfWords[sortedarray[i]]);
occurencesOfWords[sortedarray[i]] = noOfOccurences;
}
console.log(JSON.stringify(occurencesOfWords));
So you'll get something like this in the end:
{"Multimedia":3,"XYZ":2}
.search is undefined and isn't a function on the array.
But exists on the current string you want to check ! Just select the current string in the array with sortedarray[i].
Fix your code like that:
for(var i = 0; i < sortedarray.length; i++)
{
if(sortedarray[i].search("Multimedia") === true)
{
multimedia += 1;
}
}
console.log(multimedia);

Categories