Issue with my var getting undefined - javascript

I am trying to create a reverse function to the String type in javascript. My code is like
String.prototype.reverse = function () {
var s = "";
for(var i=this.length;i>=0;i--){
s+=this[i];
}
return s;
}
When I try to use it on for example like "test".reverse();
instead of giving "tset" it's giving "undefinedtset"
I am setting the variable like var s = ""; inside the function, still undefined is coming. Why is it so?

You just need to change var i=this.length to var i=this.length-1, because an array starts at position 0 :
String.prototype.reverse = function () {
var s = "";
for(var i=this.length-1;i>=0;i--){
s+=this[i];
}
return s;
}

this.length gives you 4 (4 letters in test word) and you start iterating from 4 to 0.
The problem is that nothing exists under 4 index (your letters are stored in 0-3 positions).
Try with:
for (var i = this.length - 1; i >= 0; i--) {
s += this[i];
}

The reason why your code isn't working has been answered by the others already, but if you want a shorter version of the reverse, you can do it like this:
String.prototype.reverse = function(){
return this.split('').reverse().join('');
}
console.log('Hello World'.reverse())

Related

Why Javascript console.log result is undefined while reversing the string?

var a = "gsdgtrshghf";
function reverseString(strr){
if (!strr.length){
var result="";
for(var i=strr.length;i>0;i++){
var a=strr.chatAt(i);
result+=a;
}
}return result;
}
console.log(reverseString(a))
When I tried to run it it returned me "undefined". I wonder what's the problem here.
The main reason is you are declaring var result="" and returning from outside of if(so it become undefined as its scope is only inside if statement) and other errors areas mention in comments you have a typo, charAt not chatAt. You can also simply use strr[i] to get the char. Also, you should do i-- and i >= 0 if you start at strr.length, otherwise for loop is immediately completed at the condition check. Check the below code.
var a = "gsdgtrshghf";
function reverseString(strr){
var result="";
if (strr.length){
for(var i=strr.length-1;i>=0;i--){
var a=strr.charAt(i);
result+=a;
}
}
return result;
}
console.log(reverseString(a))
Have a look:
var a = "gsdgtrshghf";
function reverseString(strr) {
var result = "";
if (strr.length != null) {
for (var i = strr.length - 1; i >= 0; i--) {
var a = strr.charAt(i);
result += a;
}
}
return result;
}
console.log(reverseString(a));
// Better
const reverse = str => Array.from(str).reverse().join('');
console.log(reverse('foo 𝌆 bar mañana mañana'));
Explanation
It's charAt(i) not chatAt(i)
Loop should start from length - 1 and end at 0 and i should be decremented
And finally declare the variable outside of if
i.e for(var i = strr.length - ; i >= 0; i--){
not for(var i=strr.length;i>0;i++){
Better yet, use combo of Array.from(str).reverse().join(''), as it even works with Unicode characters, as pointed out in comments by gaetanoM

JS: Reversing a string using nested loop does not work

I have written a function called reverseStr that takes in a string as a parameter and returns the string but with the characters in reverse.
For example: reverseStr('bootcamp'); => 'pmactoob'
Following is my program:
function reverseStr(str)
{
var splitStr = str.split("");
console.log(splitStr);
var reverseString = [];
for(var i = 0; i <= splitStr.length -1 ; i++)
{
for(var j = splitStr.length - 1; j >= 0; j--)
{
reverseString[i] = splitStr[j]
}
}
return reverseString.toString().replace(/[&\/\\#,+()$~%.'":*?<>{}]/g, '');
}
If I run the function reverseStr("bootcamp") it returns bbbbbbbb.
Does anyone see a problem with the code?
Note: I DONOT WANT TO USE REVERSE() BUILT-IN FUNCTION
However, I found success with the following code but still need an answer to my initial question
function reverseStr(str)
{
var splitStr = str.split("");
reverseStr = "";
for(var i = splitStr.length - 1; i >= 0 ; i = i - 1)
{
reverseStr += splitStr[i];
}
return reverseStr;
}
You don't need to double-iterate through the characters, i.e., do not need to nest for loops. Iterate once and grab the chars in reverse order, like this:
function reverseStr(str)
{
var splitStr = str.split("");
console.log(splitStr);
var reverseString = [];
for(var i = 0, j=splitStr.length-1; i <= splitStr.length -1 ; i++, j--)
{
reverseString[i] = splitStr[j]
}
return reverseString.toString().replace(/[&\/\\#,+()$~%.'":*?<>{}]/g, '');
}
You can see that here the loop goes on for as long as i <= splitStr.length -1,ie, length of the string. This is sufficient to get the mirroring character (i versus Array.length-i).
Here is a working snippet to demo:
var reverseStr = function(str) {
let result = String();
for(let i = str.length-1; i >= 0; i--) {
result += str.charAt(i);
}
return result.replace(/[&\/\\#,+()$~%.'":*?<>{}]/g, '');
}
$('button').click(function() {
$('.result').text(reverseStr($('#str').val()));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="str">
<button>Reverse it</button>
<div class="result"></div>
Perhaps a more elegant way to achieve the same (apart from Array.prototype.reverse()) would be to use String.prototype.chatAt(). This would avoid two conversions to and from an array, and also save you one variable. Granted, the code is much shorter and more obvious in what it is doing.
var reverseStr = function(str) {
let result = String(); // An empty string to store the result
for(let i = str.length-1; i >= 0; i--) { // Iterate backwards thru the chars and add to the result string
result += str.charAt(i);
}
return result.replace(/[&\/\\#,+()$~%.'":*?<>{}]/g, ''); // Original return method of the author
}
$('button').click(function() {
$('.result').text(reverseStr($('#str').val()));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="str">
<button>Reverse it</button>
<div class="result"></div>
The problem is that your nested for loop runs its whole course before it returns to the outer for loop. So, it just repeats one character the amount of times equal to the length. Instead of having another for loop, just add a simple counter for j like j++ inside your outer for loop and use that value with the i value.
To the original poster, consider this:
If you know the length of the original string, you therefore know the offset of that last position within the original string.
Iterate through the original string in reverse order, appending the current position's value to a new string. The new string would be the reverse of the original.
Aydin's example is essentially correct. Here's my very similar version, with comments:
function reverseString(inputString) {
// create a new empty string
var newString = "";
// iterate through the characters of the string in reverse order,
// appending to the new string
for (var i = inputString.length - 1; i >= 0; i--) {
newString += inputString[i];
}
return newString;
}
console.log(reverseString('bootcamp'));

project euler #1 , hacker rank

i am trying to do project euler # 1 with Javascript in HackerRank. Can someone give me a hints in what's wrong with my code. the result is always zero.
I run my function in my google chrome console, then i input processData(10), it gives me 23. I input processData(100), it gives me 2318.
When i try to use my code in the console from Hacker rank, it output the result as zero, like it didn't pass the first test which is 0.
Did anyone tried to solve some problem in hackerrank in javascript?
function processData(input) {
var result = []
var total=0
function findMultipleThreeAndFive(n){
var i = 0;
for(i ; i < n ;i++){
if(i%3 == 0 || i%5 == 0){
result.push(i);
}
}
}
findMultipleThreeAndFive(input)
function sum(){
for(var j = 0; j< result.length ;j++){
total += result[j]
}
return total;
}
sum()
console.log(total)
}
process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
_input += input;
});
process.stdin.on("end", function () {
processData(_input);
});
First off all, your code works: http://jsfiddle.net/azggks5a/ , but I thought I would show you how I would solve it:
I suggest you use ES6 sets, because they handle the uniqueness of your values.
I began by iterating through the multiples I wanted. I then multiplied the iterated multiple by every number upto belowThis. If the result was lower than belowThis I added the result to the set, otherwise I didn't.
Here's the code:
var multiplesOf = [3,5];
var belowThis = 10;
var multiples = new Set();
var totalOfMultiples = 0;
multiplesOf.forEach(function(element, index){
for(var i=0;i<belowThis;i++) {
if(multiplesOf[index]*i<belowThis) {
multiples.add(multiplesOf[index]*i);
}
}
});
multiples.forEach(function(element, index){
totalOfMultiples+=element;
});
console.log(totalOfMultiples);
You can change the multiples you wish to check, and to solve the question you would increase belowThis to 1000, and get a result of 233168.

Javascript - loop through number of times based on qty variable

I have the following javascript object
[Object { url="http://domain.com/abc", qty="1" }, Object { url="http://myurl.com/cde", qty="2" }]
I want to be able to loop through the object and output the URL using console.log() based on the qty variable.
So in this instance domain.com/abc would display once & the myurl.com/cde would display twice as the qty is set to 2.
I have something like the following but needs some work..
cart.forEach(function(value) {
var qty = value.qty;
var url = value.url;
var i = 0;
while ( i < qty ) {
// logic needed here (i believe)
i++;
}
}
That's how one can implement String.repeat in JS:
var repeatedString = Array(repeatsCount + 1).join(stringToRepeat);
... so in your case it'll be just ...
console.log(Array(+value.qty + 1).join(value.url));
Unary plus is a shortcut for Number(value.qty): it looks like you got a string there.
But it looks you actually need to collect all the urls instead. That's one possible way to do that:
var arrayOfUrls = [];
cart.forEach(function(value) {
for (var i = value.qty; i--) {
arrayOfUrls.push(value.url);
}
});
Alternative (.reduce-based):
var arrayOfUrls = cart.reduce(function(arr, value) {
for (var i = value.qty; i--) {
arr.push(value.url);
}
return arr;
}, []);

How to display the contents of an array after comma splitting it in Java Script

I am fairly new to Javascript and have been picking it up pretty quickly in the past few days, after staring at my code for hours and trying to figure out why it wasn't working the way I intended i figured i would post it here.
Anyways, so my question is how do I display the WHOLE content of an array after comma splitting it. My code is below. My code is only printing out the last number set that I input at the prompt.
Help would be highly appreciated.
var gradeinfo = new Object(); {
coursecode = new Array;
grade = new Array;
};
var changer = function (y) {
finalgradeinfo = new Array;
finalgradeinfo = y;
function newresults() {
var i = 0;
finalgradeinfo[i] = y;
i + 1;
}
return finalgradeinfo;
}
do {
var entry = prompt("Enter a course code and grade seperated by a comma");
if (entry != null && entry != "") {
var counter;
var entryvalid = new Array;
entryvalid = entry.split(",");
changer(entryvalid);
x = true;
} else {
x = false;
}
} while (x != false);
console.log(finalgradeinfo);
My function needs to include closure so if it looks entirely wrong i apologize in advance.
Help from this post
Split creates an array already. So, if you enter 1,2,3, you get an array like this when you split it: ["1", "2", "3"]. In your for loop, you are getting the characters from the original input, not your array. In order to add them, you need to change the input to numbers since they are considered strings. So your for loop should look like this:
for (i=0; i<3; i++)
{
entryArray[i] = parseFloat(entryArray[i]);
}
overwriting the strings with the digits.
In changer() you're destroying and recreating the array after each input. I suggest moving the array declaration into the global scope so that you can just push elements to it in the changer() function:
Fiddle
var finalgradeinfo = [];
var changer = function (y) {
finalgradeinfo.push(y);
}
do {
var entry = prompt("Enter a course code and grade seperated by a comma");
if (entry != null && entry != "") {
var counter;
var entryvalid = entry.split(",");
changer(entryvalid);
x = true;
} else {
x = false;
}
} while (x != false);
console.log(finalgradeinfo);
Notes:
Declaring arrays as [] is preferred to new Array
Not sure if you're aware but the newresults() function and gradeinfo object aren't doing anything
Also, the counter doesn't do anything, and the x boolean is unnecessary because it's basically just checking for prompt input. Here is my approach and fiddle.
var finalgradeinfo = { // declare finalgradeinfo in the global scope
coursecode: [],
grade: [] }
, entry = '';
do {
entry = prompt('Enter a course code and grade seperated by a comma') || ''; // will set entry to '' if user hits cancel
if (entry == '') continue; // break out of iteration if string is empty
var entryvalid = entry.split(",");
finalgradeinfo.coursecode.push(entryvalid[0]);
finalgradeinfo.grade.push(entryvalid[1]);
} while(entry !== '');
console.log(finalgradeinfo);

Categories