I was trying to write a function to check if "str" ends with the given "target". I eventually got the right answer but was wondering what I did wrong with the code I wrote below.
function confirmEnding(str, target) {
var targetArray = target.split("");
var strArray = str.split("");
var ending = [];
for (i=target.length; i>0; i--){
if (strArray[str.length-i]==targetArray[target.length-i]){
ending.push(targetArray[target.length-i]);
} else {
ending.push(0);
}
}
return ending==targetArray;
}
Basically so if the first letters of both str and target are the same, I added it to an array called "ending" and otherwise, added 0. Then once it's done, I would compare the two arrays and it would give me true if str does end with target and false otherwise. It only returned false and I want some insight into this. Could you give me some feedback on this? Thank you.
Since ending and targetArray are two different arrays, even if the contents are same, ending==targetArray; will not give true with '==' operator.
To check the equality of contents of arrays yo will have to iterate over each content and check the equality or if you are particular about '==' you an use
ending.toString() == targetArray.toString()
Related
I'm working on JavaScript algorithms and could use some help. What am I doing wrong exactly?
// Given an array of arr, positive integers, and another number X.
// Determine whether or not there exist two elements in arr whose sum is exactly X.
function keyPair(arr, x){
var sum=false;
var key=0;
var temp=0;
for(var i=0;i<=arr.length;i++){
while(sum=false){
key=arr[i];
arr[i]=temp;
temp=key;
}
if(temp+arr[i]==x){
sum=true;
}
}
console.log(sum);
}
keyPair([1,2,4,3,6], 4);
I think this one deserves an explanation:
sum=false is an assignment statement. As an expression, an assignment statement is evaluated as undefined (regardless of the value assigned). So while(sum=false) is actually while(undefined), which is interpreted as while(false).
Your mistake was - as explained multiple times - the wrong comparison operator. I took the liberty of rewriting your code involving a .reduce() call:
function keyPair(arr,sum){
return arr.reduce((a,c,j)=>{
let i=arr.indexOf(sum-c);
if (i>-1 && j<i) a.push([c,arr[i]]);
return a;}, []);
}
console.log(keyPair([1,2,4,3,6], 5));
I'm not going to repeat what has been already said about your code. But even if you're starting coding in JS, it pays for you to start using JS built-ins that will save you a lot of time:
// Determine whether or not there exist two elements in arr whose sum is exactly X.
So you're only interested in whether they exist, not in which are those:
const keyPair = (arr,value) =>
// some: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some
// slice: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice
arr.some( (x,i) => arr.slice(i).some( y => x + y === value));
console.log(keyPair([1,2,4,3,6], 4))
console.log(keyPair([1,1,1,1,1], 4))
With some you check if there is an x+y sum that equals to your desired value
With slice you omit the portion of the array that you don't need to check
first off, you might want to start by considering changing while(sum=false) to (sum===false), although running on vs code- it does run regardless.
I was doing this kata on codewars. The question wants the function to return true if the first argument (string) passed in ends with the 2nd argument (also a string). So I wrote my function and everything worked just fine until it compares ':-)' with ':-(' and returns true.
What is wrong? I'm so confident that my code should work that I don't even know what to search for.
function solution(str, ending){
if (!ending) return true; // if ending is a empty string return true (the question wants that)
let ok;
const strArr = str.split(''), endingArr = ending.split('');
for (let i = 0; i < endingArr.length; i++) strArr.reverse()[i] === endingArr.reverse()[i] ? ok = true : ok = false;
return ok;
}
console.log(solution(":-)",":-("));
Your problem is a misunderstanding of what reverse() does. It does not return a reversed copy of the old array, it reverses the existing array and returns that same array. As a result, you keep reversing the arrays back and forth every iteration of the loop, causing some elements to be skipped and some to be checked twice.
Array.prototype.reverse() on MDN
Edit:
As pointed out by others in the comments, both to the question and this answer, there are in fact multiple problems.
reverse() aside, the loop always sets ok to the result of the last comparison, making the function ignore all previous results.
The easier way to implement this is to remove ok altogether. Instead, return false as soon as a mismatch is detected. If the function runs long enough to exit the loop, it means no mismatch was detected and true can be returned.
Edit 2:
Just as a friendly suggestion:
While both reverse() and ok are real issues with the code, I only noticed the first one the first time around due to the formatting of the code. The ok problem was off-screen due to the line being too long. As such, once I spotted the reverse() issue, I assumed that was it and didn't bother scrolling sideways to see the rest of the code.
I am not going to demand that you write your own code in a certain way, but if you format it properly, it allows others to read it more easily. In essence, you help us to more easily help you.
For instance, this line:
for (let i = 0; i < endingArr.length; i++) strArr.reverse()[i] === endingArr.reverse()[i] ? ok = true : ok = false;
...would have been significantly easier to read as...
for (let i = 0; i < endingArr.length; i++) {
if(strArr.reverse()[i] === endingArr.reverse()[i])
ok = true;
else
ok = false;
}
...or some variation thereof. Here, the problem is significantly more visible and obvious.
The other answer explains many of the mistakes you've made. I wanted to point out just how much you've over-thought your solution.
function solution(str, ending){
if (ending === "") return true; // if ending is a empty string return true (the question wants that)
return str.endsWith(ending);
}
console.log(solution(":-)",":-("));
console.log(solution("foo",""));
console.log(solution("foo","bar"));
console.log(solution("foobar","bar"));
Even my solution above is overengineered, str.endsWith("") always returns true. So this can be simplified further.
function solution(str, ending){
return str.endsWith(ending);
}
console.log(solution(":-)",":-("));
console.log(solution("foo",""));
console.log(solution("foo","bar"));
console.log(solution("foobar","bar"));
I want to access the first two digits of a number, and i have tried using substring, substr and slice but none of them work. It's throwing an error saying substring is not defined.
render() {
let trial123 = this.props.buildInfo["abc.version"];
var str = trial123.toString();
var strFirstThree = str.substring(0,3);
console.log(strFirstThree);
}
I have tried the above code
output of(above code)
trial123=19.0.0.1
I need only 19.0
How can i achieve this?
I would split it by dot and then take the first two elements:
const trial = "19.0.0.1"
console.log(trial.split(".").slice(0, 2).join("."))
// 19.0
You could just split and then join:
const [ first, second ] = trial123.split('.');
const result = [ first, second ].join('.');
I have added a code snippet of the work: (explanation comes after it, line by line).
function getFakePropValue(){
return Math.round(Math.random()) == 0 ? "19.0.0.1" : null;
}
let trial123 = getFakePropValue() || "";
//var str = trial123.toString();
// is the toString() really necessary? aren't you passing it along as a String already?
var strFirstThree = trial123.split('.');
//var strFirstThree = str.substring(0,3);
//I wouldn't use substring , what if the address 191.0.0.1 ?
if(strFirstThree.length >= 2)
console.log(strFirstThree.splice(0,2).join("."));
else
console.error("prop was empty");
Because you are using React, the props value was faked with the function getFakePropValue. The code inside is irrelevant, what I am doing is returning a String randomly, in case you have allowed in your React Component for the prop to be empty. This is to show how you an create minimal robust code to avoid having exceptions.
Moving on, the following is a safety net to make sure the variable trial123 always has a string value, even if it's "".
let trial123 = getFakePropValue() || "";
That means that if the function returns something like null , the boolean expression will execute the second apart, and return an empty string "" and that will be the value for trial123.
Moving on, the line where you convert to toString I have removed, I assume you are already getting the value in string format. Next.
var strFirstThree = trial123.split('.');
That creates an array where each position holds a part of the IP addrss. So 19.0.0.1 would become [19,0,0,1] that's thanks to the split by the delimiter . . Next.
if(strFirstThree.length >= 2)
console.log(strFirstThree.splice(0,2).join("."));
else
console.error("prop was empty");
This last piece of code uses the conditional if to make sure that my array has values before I try to splice it and join. The conditional is not to avoid an exception, since splice and join on empty arrays just returns an empty string. It's rather for you to be able to raise an error or something if needed. So if the array has values, I keep the first two positions with splice(0,2) and then join that array with a '.'. I recommend it more than the substr method you were going for because what if you get a number that's 191.0.0.1 then the substr would return the wrong string back, but with splice and join that would never happen.
Things to improve
I would strongly suggest using more human comprehensible variables (reflect their use in the code)
The right path for prop value checking is through Prop.Types, super easy to use, very helpful.
Happy coding!
Example:
When I check a variable containing this value [""] it returns false.
var th=[]
th.push("");
if($("#multiselect").val()==th)
It returns always false.
Thank you.
Edit 1:
changed Var to var. It was a typo.
Edit 2:
Actually, the problem I faced was I was trying to get the value from a multi-select input. The multi-select input sometimes returns values as [""] even I haven't selected any values basically it's a plugin. So I was confused and I thought [""] is a fixed primitive value like 1, 10, "bla blah",.. So I tried to compare it with the same array as the right-hand side of the '=' operator.
It was stupid. Now I posted the solution to my problem and I explained my stupidity.
there are two things:
Change Var to var
You can use includes method of Array as:
var th = [] <==== chnage Var to var
th.push("");
if(th.includes($("#multiselect").val())) { <=== you can use includes method of array
// DO whatever you want
}
Make sure var is lowercased.
You are accessing th as an array, so you’ll need to specify the index of the value you are checking: th[0]
Use triple equals, too: .val()===th[0]
Double check the jquery docs if you’re still running into trouble.
Happy coding!
A couple of things to consider:
You have a typo in the code above; var is valid; Var is invalid.
Browser will aptly complain to solve this typo.
You are comparing an array to DOM value; this will always be false.
DOM is a costly process. Unless the value associated is dynamic, its better to read once, store value into a variable and continue processing instead of reading from DOM always.
You could choose to try something on these lines:
let arr = [1,2,3,4];
let domValue = $("#multiselect").val();
arr.push(5);
arr.map((el, ix) => {
if el === domValue return true; //or choose to do something else here.
});
var th=[]; //It is var not Var
th.push("");
if($("#multiselect").val()==th[0]) // change th to th[0]
I am unable to comment so having to use an answer for now. Are you trying to check if an array has any values? If so you can use
if(th.length){
// do something
}
If you want to check a normal variable for empty string you can simply use
if(th == “”){
//do something
}
I found the solution after a couple of days when I posted this question. Now I can feel how stupid this question was.
Anyway, I'm answering this question so it might help others.
Answer to my question:
When two non-primitive datatype objects(which is the Array here) are compared using an assignment operator, it compares its reference of the object. So the object creation of both arrays would be different. If I want to check the array has [""] value, I should do something like the below.
function isArrValEmptyCheck(value) {
return !value || !(value instanceof Array) || value.length == 0 || value.length == 1 && value[0] == '';
}
console.log(isArrValEmptyCheck([""]));//returns true
console.log(isArrValEmptyCheck(["value1"]));//returns false
Sorry for the late response. Thanks to everyone who tried to help me.
Exactly what title asks. I'll provide some examples while explaining my question.
Test string:
var test = "#foo# #foo# bar #foo#";
Say, I want to extract all text between # (all foos but not bar).
var matches = test.match(/#(.*?)#/g);
Using .match as above, it'll store all matches but it'll simply throw away the capturing groups it seems.
var matches2 = /#(.*?)#/g.exec(test);
The .exec method apparently returns only the first result's matched string in the position 0 of the array and my only capturing group of that match in the position 1.
I've exhausted SO, Google and MDN looking for an answer to no avail.
So, my question is, is there any better way to store only the matched capturing groups than looping through it with .exec and calling array.push to store the captured groups?
My expected array for the test above should be:
[0] => (string) foo
[1] => (string) foo
[2] => (string) foo
Pure JS and jQuery answers are accepted, extra cookies if you post JSFiddle with console.log. =]
You can use .exec too like following to build an array
var arr = [],
s = "#foo# #bar# #test#",
re = /#(.*?)#/g,
item;
while (item = re.exec(s))
arr.push(item[1]);
alert(arr.join(' '));
Working Fiddle
Found from Here
Well, it still has a loop, if you dont want a loop then I think you have to go with .replace(). In which case the code will be like
var arr = [];
var str = "#foo# #bar# #test#"
str.replace(/#(.*?)#/g, function(s, match) {
arr.push(match);
});
Check these lines from MDN DOC which explains your query about howexec updates lastIndex property I think,
If your regular expression uses the "g" flag, you can use the exec
method multiple times to find successive matches in the same string.
When you do so, the search starts at the substring of str specified by
the regular expression's lastIndex property (test will also advance
the lastIndex property).
I'm not sure if this is the answer you are looking for but you may try the following code:
var matches = [];
var test = "#foo# #foo# bar #foo#";
test.replace(/#(.*?)#/g, function (string, match) {
matches.push(match);
});
alert(JSON.stringify(matches));
Hope it helps.
data.replace(/.*?#(.*?#)/g, '$1').split(/#/)
No loops, no functions.
In case somebody arrives with a similar need to mine, I needed a matching function for a Django-style URL config handler that could pass path "arguments" to a controller. I came up with this. Naturally it wouldn't work very well if matching '$' but it wouldn't break on '$1.00'. It's a little bit more explicit than necessary. You could just return matchedGroups from the else statement and not bother with the for loop test but ;; in the middle of a loop declaration freaks people out sometimes.
var url = 'http://www.somesite.com/calendar/2014/june/6/';
var calendarMatch = /^http\:\/\/[^\/]*\/calendar\/(\d*)\/(\w*)\/(\d{1,2})\/$/;
function getMatches(str, matcher){
var matchedGroups = [];
for(var i=1,groupFail=false;groupFail===false;i++){
var group = str.replace(matcher,'$'+i);
groupFailTester = new RegExp('^\\$'+i+'$');
if(!groupFailTester.test(group) ){
matchedGroups.push(group);
}
else {
groupFail = true;
}
}
return matchedGroups;
}
console.log( getMatches(url, calendarMatch) );
Another thought, though exec is as efficient.
var s= "#foo# #foo# bar #foo#";
s= s.match(/#([^#])*#/g).join('#').replace(/^#+|#+$/g, '').split(/#+/);