Find unique value in at least two strings - javascript

if I have 10 different strings and I want to find if at least 2 that contain some value... what would the logic be on that?
all "and's" does not work and neither does all "or's"
Below won't work...
This will only work if every one has value...
if(str1 && str2 && str3 && str4 && str5 && str6 && str7 && str8 && str9 && str10)
This will be true if there is only one value... needs to be at least 2
if(str1 || str2 || str3 || str4 || str5 || str6 || str7 || str8 || str8 || str10)
Is there any easy way to do this?
Edit: More info...
There is going to be ten long strings and I need to chunk through them and check (for instance) if any of the first characters are the same, then check if any of the second characters are the same etc. but I can add all the extra "charcode at" stuff in later. The same answer will work for checking full length strings and finding if two are the same.

Put all strings in an array say myArray and count strings having the value and see if count is greater than or equal to 2
var count = 0;
for (var index=0; index<myArray.length; index++) {
if(myArray[index].indexOf(value) != -1) {count++;}
if(count==2) break;
}
if(count==2){alert("atleast 2 have value");}
else {alert("Less than 2 have value");}

Add each string to an array and then iterate the array, incrementing a counter every time a match is found:
var val = "search string here";
var arr = [str1, str2, str3, str4, str5, str6, str7, str8, str9, str10];
var matches = 0;
for (var i = 0; i < arr.length; i++) {
if (arr[i].indexOf(val) > -1 && ++matches >= 2) break;
}
if (matches >= 2) {
alert("validates");
} else {
alert("failed");
}

It's a little unclear what you're asking. If you want to check if at least two of the strings are duplicates of each other, then the following should do:
function duplicatesExist (array) {
var hash = {};
for ( var i = 0 ; i < array.length ; i++ ) {
if ( hash.hasOwnProperty(array[i]) ) return true;
else hash[array[i]] = true;
}
return false;
}
duplicatesExist([str1, str2, str3, ...]);

Make an array containing the ten strings. Create a "nonEmptyItemCount" variable (or similar) and set it to zero. Loop through the array, testing the current item, and if it has a value increment nonEmptyItemCount. When you are done looping, see if nonEmptyItemCount >= 2

To test the number of strings that are not empty it is easy to build an array of those strings (let's call it arrayOfStrings). The number of not empty strings you can find with
arrayOfStrings.filter(function(s) { return s }).length
I hope this is what you were looking for. To explain it: filter returns all elements of the array where the function returns true. The filter function gets the string as an argument. We just return it and while javascript is coercing the value into a boolean every empty string will evaluate to false. This leaves only the not empty ones in the result. A length of the resulting array is the number you are looking for and you compare it to your wanted minimum

Related

Check length between two characters in a string

So I've been working on this coding challenge for about a day now and I still feel like I haven't scratched the surface even though it's suppose to be Easy. The problem asks us to take a string parameter and if there are exactly 3 characters (not including spaces) in between the letters 'a' and 'b', it should be true.
Example: Input: "maple bread"; Output: false // Because there are > 3 places
Input: "age bad"; Output: true // Exactly three places in between 'a' and 'b'
Here is what I've written, although it is unfinished and most likely in the wrong direction:
function challengeOne(str) {
let places = 0;
for (let i=0; i < str.length; i++) {
if (str[i] != 'a') {
places++
} else if (str[i] === 'b'){
}
}
console.log(places)
}
So my idea was to start counting places after the letter 'a' until it gets to 'b', then it would return the amount of places. I would then start another flow where if 'places' > 3, return false or if 'places' === 3, then return true.
However, attempting the first flow only returns the total count for places that aren't 'a'. I'm using console.log instead of return to test if it works or not.
I'm only looking for a push in the right direction and if there is a method I might be missing or if there are other examples similar to this. I feel like the solution is pretty simple yet I can't seem to grasp it.
Edit:
I took a break from this challenge just so I could look at it from fresh eyes and I was able to solve it quickly! I looked through everyone's suggestions and applied it until I found the solution. Here is the new code that worked:
function challengeOne(str) {
// code goes here
str = str.replace(/ /g, '')
let count = Math.abs(str.lastIndexOf('a')-str.lastIndexOf('b'));
if (count === 3) {
return true
} else return false
}
Thank you for all your input!
Here's a more efficient approach - simply find the indexes of the letter a and b and check whether the absolute value of subtracting the two is 4 (since indexes are 0 indexed):
function challengeOne(str) {
return Math.abs(str.indexOf("a") - str.indexOf("b")) == 4;
}
console.log(challengeOne("age bad"));
console.log(challengeOne("maple bread"));
if there are exactly 3 characters (not including spaces)
Simply remove all spaces via String#replace, then perform the check:
function challengeOne(str) {
return str = str.replace(/ /g, ''), Math.abs(str.indexOf("a") - str.indexOf("b")) == 4;
}
console.log(challengeOne("age bad"));
console.log(challengeOne("maple bread"));
References:
Math#abs
String#indexOf
Here is another approach: This one excludes spaces as in the OP, so the output reflects that. If it is to include spaces, that line could be removed.
function challengeOne(str) {
//strip spaces
str = str.replace(/\s/g, '');
//take just the in between chars
let extract = str.match(/a(.*)b/).pop();
return extract.length == 3
}
console.log(challengeOne('maple bread'));
console.log(challengeOne('age bad'));
You can go recursive:
Check if the string starts with 'a' and ends with 'b' and check the length
Continue by cutting the string either left or right (or both) until there are 3 characters in between or the string is empty.
Examples:
maple bread
aple brea
aple bre
aple br
aple b
ple
le
FALSE
age bad
age ba
age b
TRUE
const check = (x, y, z) => str => {
const exec = s => {
const xb = s.startsWith(x);
const yb = s.endsWith(y);
return ( !s ? false
: xb && yb && s.length === z + 2 ? true
: xb && yb ? exec(s.slice(1, -1))
: xb ? exec(s.slice(0, -1))
: exec(s.slice(1)));
};
return exec(str);
}
const challenge = check('a', 'b', 3);
console.log(`
challenge("maple bread"): ${challenge("maple bread")}
challenge("age bad"): ${challenge("age bad")}
challenge("aabab"): ${challenge("aabab")}
`)
I assume spaces are counted and your examples seem to indicate this, although your question says otherwise. If so, here's a push that should be helpful. You're right, there are JavaScript methods for strings, including one that should help you find the index (location) of the a and b within the given string.
Try here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#instance_methods

How to check string length in JavaScript?

How can I check the length of in String in JavaScript? Here is a small code example:
if(value != null && value != "" && value.length !== 10 && !value.match(/^\d*$/)){
// do something
}
The expression 'value.length !== 10' doesn´t work. A String must contain at least 10 characters. How can I solve this problem?
Instead of match, test can be used with proper regex \d{10,}.
if (value && /^\d{10,}$/.test(value.trim()))
To Get the string length of a value for example:
var value="This is a string";
var string_length=value.length;
/*The string length will result to 16*/
Hope this helps
var regex = new RegExp(/^\d*$/),
value = $.trim("1234567890");
if (value.length >= 10 && regex.exec(value)) {
// correct
} else {
// incorrect
}

How to successfully break out of function in javascript?

So I have a function that checks if the last character in a string is an arithmetic operator(+,-,*,/), and if it is it should immediately return from the function. If not, the subtract sign should be appended to the string. However, only the second case seems to be occurring and I can't figure out why. If anyone could provide some insight I would be very appreciative.
$("#subtract").click(function () {
var original=$("#display").text();
var sliced=original.slice(0,original.length - 1);
var signs=["+","-","*","/"];
var charpos=sliced.charAt(sliced.length -1);
if ((charpos === signs[0]) || (charpos === signs[1]) || (charpos === signs[2]) || (charpos === signs[3])) {
return;
}
else {
var newdisplay=sliced + "-";
$("#display").text(newdisplay);
}
});
You're slicing the input which is removing the last character, then using charAt and getting the second to last character.
var original=$("#display").text(); // "foobar"
var sliced=original.slice(0,original.length - 1); // "fooba"
var charpos=sliced.charAt(sliced.length -1); // "a" -- we lost the "r"
You only need to call charAt and work with the last character (or, if you prefer slice, it's able to accept a negative number and backtrack the string).
Secondly, since signs is an array, you can use indexOf over checking each element. e.g.
var original = $('#display').text();
var signs = ["+","-","*","/"];
var lastChar = original.slice(-1); // OR original.charAt(original.length - 1);
// Check for the lastChar in the signs array
if (signs.indexOf(lastChar) != -1){ // -1 == not found
return; // short exit
}
var original=$("#display").text();
var sliced=original.slice(0,original.length - 1);
the second line gets rid of the last character in your string. so you're not even able to check what that was. just get rid of it and change the first line to
var sliced=$("#display").text();
and everything should work fine
Instead of
if ((charpos === signs[0]) || (charpos === signs[1]) || (charpos === signs[2]) || (charpos === signs[3])) {
return;
}
try
if ($.inArray(charpos, signs) > -1) {
return;
}
First of all, never enumerate items from an array in such a fashion - it's easy to miss items that way. Secondly, exact instance comparison (===) won't fire, unless you compared exact same strings.
Besides, consider revising how you extract the last character.

checking if digit exists on particular place in string

I have a string that starts with "TT" and ends with six digits(ex. "TT012345", "TT012000, TT329001). The string is always formatted like this and I need to check if the last digit in this string is of a certain value.
Say I have the string "TT032970". In this case I'd like to get a match on this string since the last digit is zero and the digit before that is a seven(I'm looking for 7).
The string "TT037000" should also be a match but "TT0329701" shouldn't(since it isn't all zeroes to the right of the seven(the "last" 7 in the string)).
I was thinking of using a set of nested if's using substr() to check all places of the string for zeroes and if it isn't a zero in position n, then I check if the digit I'm looking for exists in position n.
My code is repetitive and I'm all for being efficient.
This is what I got so far(that works but only checks the last place of the string and the second last place):
var lastDigit = [3, 7, 8], tda = document.querySelectorAll('td a'), i, j;
function checkArray(num) {
"use strict";
for (j = 0; j < lastDigit.length; j++) {
if (num === lastDigit[j]) {
return true;
}
}
}
for (i = 0; i < tda.length; i++) {
if ((parseInt(tda[i].textContent.substr(8, 1), 10) === 0 && checkArray(parseInt(tda[i].textContent.substr(7, 1), 10))) || checkArray(parseInt(tda[i].textContent.substr(8, 1), 10))) {
tda[i].style.background = "rgb(255, 144, 255)";
amountOfTickets.push(tda[i]);
}
}
I'm positive there's a great way of checking the string for trailing zeroes and check the first non-zero digit before the zeroes. However, I'm really bad with loops and I just can't figure out how.
I'm very keen on figuring it out myself but I need a head start. I'd rather take a detailed explanation on how to do it than just the "answer".
If anything else seem off I'd gladly listen to improvements.
Thanks in advance!
To get the first digit before the zeros at the end of a string, you may use a regular expression :
+string.match(/(\d)0*$/)[1]
Example 1 :
var string = "TT032970";
var digit = +string.match(/(\d)0*$/)[1];
console.log(digit); // logs 7
Example 2 :
console.log(["TT012345","TT012000","TT329001","TT032970"].map(function(string){
return +string.match(/(\d)0*$/)[1]
})); // logs [5, 2, 1, 7]
Demonstration
Obviously, from the other answers, a regular expression will be much simpler than your loops. Moreover, any nested loop solution will be difficult to work, as you don't know how many levels deep you have to look. (Is there one zero? Two? Five?)
This regex is quite simple:
/(\d)0+$/
If you do a match on that with your string, you should get either null if it doesn't match (e.g. "TT0329701") or a two-element array if it does (e.g. "TT037000" will return ["7000", "7"].)
That should be enough for your to build your own solution upon.
Best of luck.
The first thing I though about is something like this (depends on whether I understood your problem correctly):
function lookFor(str, digit) {
//validate input...
if (str.length != 8) return false;
if (str[0] != "T" && str[1] != "T") return false;
//start at the end and move to the left as long as there are zeros
//the first non-zero element must be our digit, else return false
for (var i = str.length-1; i>0; --i) {
if (str[i] !== "0") {
return str[i] === digit;
}
}
}
lookFor("TT012000", "2") --> true
lookFor("TT012000", "3") --> false
But I guess the regex solution is probably more compact than this one.

Javascript syntax issue

Here is my jsFiddle
Its on the Phone method, no the name one
Now is this line right? I only want it to be true if the first 3 letters are 087
var RightStarting3 = value.substring(0,2) == (087);
if (BlankPass || LessThan10 || RightStarting3 || GreaterThan10 || (HasSpaces > 0))
{
document.getElementById('Phone').style.background = "red";
return false;
}
else {
document.getElementById('Phone').style.background = "white";
document.getElementById("PhoneTick").style.visibility="visible";
return true;
}
var RightStarting3 = value.substring(0,3) === ('087');
value.substring(x) returns a string and 087 and 87 mean the same to javascript interpreter. You should change one of the datatypes so that they match...
Either the substring to an integer:
var RightStarting3 = parseInt(value.substring(0,2)) == 87;
Or the value you're comparing against to a string:
var RightStarting3 = value.substring(0,3) == "087";
Secondly -- you are invoking ValidateName() immediately (in your assignment to NamePass). Is this really necessary? There will be empty values on page load.
I think with the javascript substring(x,y) method, the y value is the value at which to stop the selection. So in your example the first 3 characters will not be selected and instead the first 2 characters will be selected.
var a = "123";
// this returns "12"
alert(a.substring(0,2));
You probably want to use var RightStarting3 = value.substring(0,3) == ('087'); instead.
KingKongFrom's answer is correct, I would add that you should make sure that value (whatever that is) isn't null first, cause if you try to call substring on null it will thrown an exception and die.

Categories