Value keeps returning as undefined - javascript

Not sure why i keep getting undefined for this results any help would be great. The result is suppose to the the array with the x value at the beginning. thanks
var tester = [1,2,4];
Array.prototype.cons = function(x){
function reduce(results,y){
if(y == 1){
results.unshift(x);
return results;
}
else{
results.push(this[y-1]);
y = y-1;
reduce(results, y);
}
}
return reduce([], this.length);
}
document.getElementById('test').innerHTML = tester.cons(0)

You designed your reduce function to return results, but in your recusive call of it
else{
results.push(this[y-1]);
y = y-1;
reduce(results, y); // <--- HERE
}
You aren't doing anything with the returned value (such as returning it up the stack). This means that evaluation continues down your function, at the bottom of which there is no return statement. In JavaScript, no return statement means that the return value of the function call will be undefined

If you're just trying to move an element in the array to the front, you can simply use this instead of recursively going through the array.
var tester = [1,2,4];
Array.prototype.cons = function(x){
// Copy the array. This only works with simple vars, not objects
var newArray = this.slice(0);
// Check to make sure the element you want to move is in the array
if (x < this.length) {
// Remove it from the array
var element = newArray.splice(x, 1);
// Add to the beginning of the array
newArray.unshift(element);
}
return newArray;
}
document.getElementById('test').innerHTML = tester.cons(4)​;​
EDIT: Made a copy of the array

Related

Why does this javascript function keep returning an array as undefined?

I have this simple function "decode" that takes in 2 arrays as input, where the second array is used to decode the first array.
The starting input (not when the function recurses) must always be of the following format:
1st array is of length 1
2nd array is of a length that is a power of
2, minus 1 (1,3,7,15,...)
Example input:
([4],[0,2,6])
For some reason, my code always returns undefined when I try to return a decoded array. In fact, I can't seem to return anything other than undefined, even when I change the return statement to something like "return false". The log statements show that the correct values are being captured for both arrays, leaving me very confused.
Here's my code:
var decode = function(A, B){
console.log("A: "+A+" B:"+B);
console.log(B.length);
if(B.length===0){
return A;
}
var newA = [];
var newB = [];
var act = 0;
for(let i=0; i<A.length; i++){
newA[act] = A[i] - (B[i]/2);
newA[act+1] = A[i] + (B[i]/2);
act+=2;
newB = B.slice(i+1);
}
decode(newA, newB);
}
console.log("Answer is" + decode([4], [0,2,6]));
This will always return undefined, regardless of what you make the return statement. Console.log(A); on the other hand is giving me the correct value for what I want to return.
Thank you very much for the help! Greatly appreciated.
The problem is that if B.length != 0, there is no return value.
Change
decode(newA, newB);
to
return decode(newA, newB);

using javascript to code the preorder traversal

var preorderTraversal = function(root) {
var array = [];
if(!(root == null)){
array.push(root.val) ;
preorderTraversal(root.left);
preorderTraversal(root.right);
}
return array;
};
The code failed in testing when the test case is [1,2], I only output [1], how to fix it?
The problem is that you're creating a new, separate array in each recursive call (and then discarding it, since you don't do anything with what the recursive calls return).
An alternative approach is to pass in an "accumulator" array acc, and pass it to every recursive call, so that all elements get added to a single array:
var preorderTraversal = function(root, acc = []) {
if(!!root){
acc.push(root.val);
if (root.left) preorderTraversal(root.left, acc);
if (root.right) preorderTraversal(root.right, acc);
}
return acc;
};
You might also be interested in traversing pre-ordered BST iteratively, instead of recursively:
var preorderTraversal = function(root) {
/**
* Algorithm:
* 1. Create an empty stack [];
* 2. Do while stack is not empty:
* 2.1. Pop an item from stack and add it to the 'result' array.
* 2.2. Push 'right child' of popped item to stack.
* 2.3. Push 'left child' of popped item to stack.
*/
if (root == null) {
return [];
}
const stack = [];
const result = [];
stack.push(root);
while(stack.length > 0) {
let current = stack.pop();
result.push(current.val);
if (current.right) stack.push(current.right);
if (current.left) stack.push(current.left);
}
return result;
};
array is a local variable then:
you put 1 on array with push
recursively go to others sides when you create again array = []
push 2
when you return to your top of recursion stack array still have only 1
maybe is better if you can send array as argument, and use returned array for modify the local one
You will need a helper function for inline printing for js; this helper function should call your actual preorder function.
Inside of your preorder function, you need to always keep updating the string "passed" (I explain the "" afterwards). If current node is empty, you should return the current string you have at the moment, otherwise it would wipe it off.
function doPreOrder(root, str) {
if(!root) {
return str;
}
if(!str) {
str = "";
}
if(root) {
str += root.val + ' ';
str = doPreOrder(root.left, str);
str = doPreOrder(root.right, str);
}
return str;
}
function preOrder(root) {
var x = doPreOrder(root);
console.log(x);
}
As you can see, we first need to use the function, and only pass root. We're passing an undefined var to it, and it will be the only time we will enter the str = "" code, and then from that point on, the str will update for each new data. At the end, you just console log that var.

Checking if one element of an array's index is equal to the second element

I have this little script that will check if one element of an array (arr[0]) is equal to the second element of the array (arr[1]). However when it checks the following array I would expect it to return false, yet it returns true. so my questions are, why does this return true, and how can I fix it to return false like expected?
function mutation(arr) {
var elem0 = arr[0].toLowerCase();
var elem1 = arr[1].toLowerCase();
for(var x=0; x < elem1.length; x++){
check = elem0.indexOf(elem1[x]);
if(check === -1){
return false;
}
return true;
}
}
mutation(["hello", "hey"]); //returns true
you place the return true to soon
you need to place it after the for statement like so
function mutation(arr) {
var elem0 = arr[0].toLowerCase();
var elem1 = arr[1].toLowerCase();
for(var x=0; x < elem1.length; x++){
check = elem0.indexOf(elem1[x]);
if(check === -1){
return false;
}
}
return true;
}
mutation(["hello", "hey"]); //returns false
You're looping over a characters in a string (see what elem1 actually is), and therefore you get true because the first character of hey, which is h, is indeed found within the string hello.
If you want to wait for it to finish iterating over the whole string, use a boolean flag, and then return the value of that flag when the iterations are over.
However, seems you just want to compare the two elements:
return elem0 === elem1;
I have this little script that will check if one element of an array
(arr[0]) is equal to the second element of the array (arr[1])
It returns true since e is in both the elements hello and hey
Your code is essentially iterating over all the characters in the string.
You need to simply check
function mutation(arr) {
return arr[0].toLowerCase() == arr[1].toLowerCase();
}
The expression of this question has some logical flaws or at least some lacking points. Such as the given condition means that all the items in the array must be equal. If this is the case then just one tiny piece of instruction is sufficient
myArray.every(e => e == myArray[0])
var a = [1,1,1,1,1,1,1,1],
b = ["hello", "hey"];
document.write("<pre> a array :" + a.every(e => e == a[0]) + "</pre>");
document.write("<pre> b array :" + b.every(e => e == b[0]) + "</pre>");

Self Invoking Function returns "undefined"

Im trying to get a sum of array injected into a function that loops until all the values are added, the console.log right before the "return" logs the right value, meaning the code works, but when I try to use that function with any array it returns "undefined"...
var total = function(arr) {
console.log(arr);
if(arr.length > 1) {
var temp = []
for(var i=0, len=arr.length-1; i<len; i++) {
temp.push(arr[i] + arr[i+1]);
}
total(temp);
}
else {
console.log(arr.join()); // 48, exectly what I need
return parseInt(arr.join());
}
}
var sup = total([1,2,3,4,5]); // undefined
Not completely sure how to debug it..
If your arr.length is greater than one, you will invoke total with the temporary array, however, you don't do anything with this temporary array - you don't return it, or utilize it in any way, so the intermediate results are lost.
In addition - this is not a self invoking function; it is recursion.

Why does the return value in function f return the display function instead of x value

hi a would like to ask why this code returns a function and not the x value.
Thanks in advance.
function f() {
function makeClosure(x) {
return function(){
return x;
};
}
var a = [];
var i;
for(i = 0; i < 3; i++) {
a[i] = makeClosure(i);
}
return a;
}
var a = f();
console.log(a[0]);
makeClosure is returning functions, so your array a is filled with functions.
a[0] will return the function, a[0]() will return x
If you look at makeClosure you will see that it returns a function that in turns returns x.
Within the loop a[i] = makeClosure(i); assigns the function returned by makeClosure(i) in the array at the i index.
Running a function at a specific index in the array will return the related x value.
a[0](); should return 0.
Function f() returns an array.
So var a=f() assigns an array in a.
Now each array element is itself a function. So if you access any array element in the array a it will simply access the function definition but will not execute it.
Hence to execute the function you need to call the array elements as a function i.e. in place of a[0] in console.log(a[0]); you need to use console.log(a[0]());
This was the only reason...

Categories