Compare two array and find match in Javascript - javascript

for(var i = 0; i < textList.length; i++){
for(var j = 0; j < titles.length; j++){
if(textList[i] === titles[j]){
console.log ("it includes my " + titles[j] + ' the match is ' +textList[i] + " counter " + i)
}
}
}
this is my code, but it won't return a match. I tried == and ===. But when i tested .includes() it worked. Can someone explain what's happening ?

If you are sure that all elements are in type String, you can use the method .search():
Prototype search
It will return the position of the match, if it dosent match in any position you will get -1 as return, soo > 0 it match.

I just tested your code with a very basic test example as follows:
let textList = ['book1', 'book2','book3']
let titles = ['book', ' tester', 'not_this', 'book2']
for(var i=0; i<textList.length;i++){
for(var j=0; j<titles.length;j++){
if (textList[i] === titles[j]){
console.log ("it includes my " + titles[j] + ' the match is ' +textList[i] + " counter " + i)
}
}
}
And I got the expected result it includes my book2 the match is book2 counter 1 so with this specific code I would suggest looking at you input arrays.
With regards to your question regarding why .includes() works and this doesn't, again we would need to se your input arrays but I would hazard a guess that it is something to do with the type checking within this function.
Finally, as others have suggested, there are other (more succinct) ways of achieving this with built in array functions, however your original question was about why this code in particular doesn't work so I've left these out.

Related

Problems with IF condition

I'm trying to make a website that gathers information from APIs. The following code always evaluates to 'Beep Boop Beep! I can\t find the Wikipedia page with the API! :-( \n Anyways here is more info on...'! Anyone have any ideas why?
var geoNamesWiki = result.geoNamesWiki;
for (let j = 0; j < 30; j++) {
if (geoNamesWiki.geonames[j].feature == 'country' &&
(geoNamesWiki.geonames[j].countryCode == openCage.results[0].components["ISO_3166-1_alpha-2"] ||
geoNamesWiki.geonames[j].title.includes(openCage.results[0].components.country))) {
$('#summary').html(geoNamesWiki.geonames[j].summary);
$('#wikiLink').html(geoNamesWiki.geonames[j].wikipediaUrl).attr("href", "https://" + geoNamesWiki.geonames[j].wikipediaUrl);
} else {
$('#summary').html('Beep Boop Beep! I can\t find the wikipedia page with the API! :-( \n Anyways here is more info on' + openCage.results[0].components.country + ':');
$('#wikiLink').html('https://en.wikipedia.org/wiki/' + encodeURI(openCage.results[0].components.country)).attr("href", 'https://en.wikipedia.org/wiki/' + encodeURI(openCage.results[0].components.country));
}
}
Is suspect you have a string there at var geoNamesWiki = result.geoNamesWiki;
Try parsing it to a JSON object first var geoNamesWiki = JSON.parse( result.geoNamesWiki );
I found the answer thanks to #Bekim Bacaj! I was overwriting what I had already done, so just needed to add a break on the final line of the IF part.

jquery put comma between every variable except last

I have a script that will insert the checked checboxes and radios in the value() of an input tag.
var burgernavn = meat + " with " + bread + " and " + onion + tomato + cheese + salad;
$('#burger-navn').val(burgernavn);
Onion, tomato, cheese and salad needs to have1 " ," between them, except the last two who need " and " between them.
Thats the first thing.
Second thing is that these variables represent checkboxes, so they can be undefined, in which case they should not be put into $('#burger-navn').val(). They can all be undefined, in which case no commas or "and" should be put in.
I hope this is accomplishable.
Capture all checked values in an array (this makes sure that whatever values in this array, all are defined). Also, it will give you count of values that you need to pass to input box.
var checkedValues = document.getElementsByClassName('checkbox');
Iterate over this array, check for last values. (Check my comments in below code snippet)
var commaValues = "", otherValues= "";
//we are iterating only until (total values -2)
for(var i = 0; i < checkedValues.length - 2 ; i++){
//append comma with each value
commaValues += checkedValues[i].concat(",");
}
//append 'And' for last two values if total valuesa re more than one
if(checkedValues.length > 1){
otherValues = checkedValues[checkedValues.length-1].concat("and", checkedValues[checkedValues.length])
}
else if(checkedValues.length == 1){
otherValues = checkedValues[0];
}
//finally concat both strings and put this concated string in input
$('#burger-navn').val(otherValues.concat(commaValues));
So, I hope you got the idea. This code snippet might need a bit tweak since I didn't had your html code and sample data, but it is easily doable using this snippet as reference. Cheers
You can do this pretty easy with jQuery $.map.
var checkboxes = $('input:checkbox');
var commaString = $.map($('input:checkbox'), function( ele, i ) {
return $(ele).val() + (i + 2 == checkboxes.length ? " and" : (i + 1 != checkboxes.length) ? ",": "");
}).join(" ");

Why am I getting weird increments in my for loop?

I have been testing ways to check individual characters in a string for a numeric value. I set up a for loop that goes through them, but when I'm logging it to the console, I get a weird response:
isNumeric: function(n){
for(var i = 0; i < n.length; i++){
console.log("Looping " + i+1);
}
},
So I passed in the value "10" to test it. I get a weird response when I call the function. I get two logs onto the console (like expected), but it says
Looping 01
Looping 11
What is going on here? I didn't think that I was concating strings here, but for some reason it thinks I am? I declared i as an integer var i = 0; and when you increment it by one, what is it doing?
The only other thing I think it must be doing is logging something else appended to Looping 0 and Looping 1, but I don't think that's the case.
If anyone can please help, this is really bugging me and I can't seem to fix it.
Thanks in advance.
+ is left-to-right associative. The expression is evaluated as
('Looping ' + i) + 1
Is it clearer now why string concatenation is performed? If any of the two operands of a + operation is a string, string concatenation is performed. 'Looping ' is a string, hence 'Looping ' + i results in a string.
To change precedence or associativity, you have to use the grouping "operator" ((...)).
You mean console.log("Looping " + (i+1));
The "1" is being appended as a string.
console.log("Looping " + i+1); is being parsed from left to right, as ("Looping " + i) + 1. Add parentheses in the right spot and it should work:
console.log("Looping " + (i+1));
You are concatenating strings, not adding numbers. First, the value of i is cast to a string and concatenated to Looping, resulting in Looping 0. Then, the number 1 is cast to a string and concatenated as well, resulting in what you are seeing: Looping 01.
To get the result you want, you can simply put the i+1 in parentheses.
console.log("Looping " + (i+1));
the problem lies in the line where you do the actual logging :
console.log("Looping " + i+1);
First "Looping " + i happens.
Because "Looping" is a string, i gets cast to a string and appended to "Looping".
The result :
"Looping 0"
Then, the 1 gets added the same way.
"Looping 01"
If you want to keep this from happening, use parenthesis like so :
isNumeric: function(n){
for(var i = 0; i < n.length; i++){
console.log("Looping " + (i+1));
}
},
They are right to add the parentheses, the whole code would be:
isNumeric: function(n){
for(var i = 0; i < n.length; i++){
console.log("Looping " + (i+1));
}
},
Compare your results with this:
n=[1,2,3,4]
function isnum(n){
for(var i = 0; i < n.length; i++){
console.log("Looping " + i+1);
console.log("Looping " + (i+1));
}
}
isnum(n);
This generates the output:
Looping 01
Looping 1
Looping 11
Looping 2
Looping 21
Looping 3
Looping 31
Looping 4
In the statement "Looping " + i+1 what's happening is that "Looping " + i is happening first, i being cast to a string value for the concatenation with "Looping ". The 1 is also being cast as a string value for concatentation. By putting parens around the i+1 we can force (i+1) to happen first as addition before being concatenated, so the output is what you would expect.

.replace method in JavaScript and duplicated characters

I'm trying to use JavaScript to insert HTML ruby characters on my text. The idea is to find the kanji and replace it with the ruby character that is stored on the fgana array. My code goes like this:
for (var i = 0; i < kanji.length; i++) {
phrase = phrase.replace(kanji[i],"<ruby><rb>" + kanji[i] + "</rb><rt>" + fgana[i] + "</rt></ruby>");
}
It does that just fine when there aren't duplicated characters to be replaced, but when there are the result is different from what I except. For example, if the arrays are like this:
kanji = ["毎朝","時","時"]
fgana = ["まいあさ"、"とき"、"じ"]
And the phrase is あの時毎朝6時におきていた the result becomes:
あの<ruby><rb><ruby><rb>時</rb><rt>じ</rt></ruby></rb><rt>とき</rt></ruby><ruby><rb>毎朝</rb><rt>まいあさ</rt></ruby> 6 時 におきていた。
Instead of the desired:
あの<ruby><rb>時</rb><rt>とき</rt></ruby><ruby><rb>毎朝</rb><rt>まいあさ</rt></ruby> 6 <ruby><rb>時</rb></ruby></rb><rt>じ</rt> におきていた。
To illustrate it better, look at the rendered example:
Look at how the first 時 receives both values とき and じ while the second receives nothing. The idea is to the first be とき and the second じ (as Japanese has different readings for the same character depending on some factors).
Whats might be the failure on my code?
Thanks in advance
It fails because the char you are looking for still exists in the replaced version:
...replace(kanji[i],"<ruby><rb>" + kanji[i]...
And this one should work:
var kanji = ["毎朝", "時", "時"],
fgana = ["まいあさ", "とき", "じ"],
phrase = "あの時毎朝 6 時におきていた",
rx = new RegExp("(" + kanji.join("|") + ")", "g");
console.log(phrase.replace(rx, function (m) {
var pos = kanji.indexOf(m),
k = kanji[pos],
f = fgana[pos];
delete kanji[pos];
delete fgana[pos];
return "<ruby><rb>" + k + "</rb><rt>" + f + "</rt></ruby>"
}));
Just copy and paste into console and you get:
あの<ruby><rb>時</rb><rt>とき</rt></ruby><ruby><rb>毎朝</rb><rt>まいあさ</rt></ruby> 6 <ruby><rb>時</rb><rt>じ</rt></ruby>におきていた
Above line is a bit different from your desired result thou, just not sure if you indeed want this:
...6 <ruby><rb>時</rb></ruby></rb><rt>じ</rt>...
^^^^^ here ^ not here?

Counting the words that search inside a string

Using javascript prompt I get two parameters like, search string and search keyword, then search for the keyword and get the number of items found. Then need to show them on the page. Seems to mistake I have made.
<html>
<head>
<script type = "text/javascript">
var counter = 0;
var enter = prompt("Enter your String:");
var search = prompt("Enter words to search:");
var b = search.length;
var a = enter.length - search.length;
for (var y = 0; y <= a; y++)
{
if(b <= enter.length){
if(enter.substring(y,B))
{
counter = counter + 1;
}
b++;
}
else{
document.write("<p>" + "ERROR" + "</p>");
}
document.write("<p>" + "your word:" + enter + "</p>");
document.write("<p>" + "word use:" + counter + "</p>");
</script>
<body>
</body>
</head>
</html>
You are using a variable that is not declared. Remember that Javascript is case sensitive and the variable b is different than B.
You forget to close the for brackets.
You need to compare the substring with the search pattern.
As Sameera Thilakasiri has rightly pointed out, your code is sloppy. If that works for you, great (I suppose), but other people who look at your code may have a hard time following it. Further, sloppy code leads to mistakes that would otherwise be easily caught.
For instance, you have not closed the for loop, which would easily be seen in nicely formatted code.
Beyond the open for loop, the only other problem I see (syntactically) is that JavaScript is a case-sensitive language, which means that b is different from B, which is why your script throws the 'Uncaught ReferenceError: B is not defined' on the line if (enter.substring(y,B)) {.
Try closing your for loop and using a lowercase b on the offending line. Once that is done, you only have to fix the logic errors.
Happy coding.
You can also use indexOf:
var counter = 0;
var enter = prompt("Enter your String:");
var search = prompt("Enter words to search:");
var start = 0;
while(1){
start = enter.indexOf(search,start);
if(start==-1) break;//if nothing found
start++;//next start = current occurrence + 1
counter++;
}
document.write("<p>" + "your word:" + enter + "</p>");
document.write("<p>" + "word use:" + counter + "</p>");

Categories

Resources