Undefined array parameter with Javascript - javascript

I can't see why this function is returning undefined:
function sumArray(array) {
array.reduce(function(result, item) {
return result + item;
})
}
array = [1,2,3]
sumArray(array)
I've tried something similar and it works ok (below), so I'm not sure if it's specific to the parameter being an array?
function sayNumber(num) {
return num + 1;
}
num = 1
sayNumber(num)

What you actually need is to add one more return statement.
function sumArray(array) {
//here
return array.reduce(function(result, item) {
return result + item;
});
}
array = [1,2,3];
sumArray(array);
//6

The function sumArray is not returning the result from array.reduce. Insert a return before your array.reduce.

It returns undefined because there is no return statement for the sumArray function.
(The anonymous function you pass to reduce has one, but that is a different function).
If you want to return the result of calling array.reduce when you have to say so explicitly:
return array.reduce(etc, etc…

You should return the value of the function sumArray
Like this:
function sumArray(array) {
return array.reduce(function(result, item) {
return result + item;
})
}

Related

I keep getting "undefined" as an error, function not returning anything

I've been trying to figure out why I keep getting undefined, and I don't really see why, I know that I would get undefined if my function isn't returning anything, but in this case, even with returning in two places, I am still getting undefined. I think that the reason for that is that maybe I am not returning the value from innerFunc properly? I'm thinking maybe there's something wrong with my syntax here: innerFunc(arg) but I'm not sure how it is wrong, or what to change it to.
Any help would be appreciated.
Instructions:
Create a function "fastCache" that takes one argument (a function) and returns a function. When fastCache is invoked it creates an object that tracks calls to the returned function, where each input to the returned function is associated with its output. Every subsequent call to that returned function with the same argument will return the output directly from the object, instead of invoking the original function again.
function fastCache(func) {
const obj = {};
function innerFunc(arg) {
for (const key in obj) {
if (key === arg) {
return obj[arg]
} else {
obj[arg] = innerFunc(arg)
return innerFunc(arg)
console.log(obj[arg])
console.log(arg)
console.log(innerFunc(arg))
}
}
}
return innerFunc
// console.log(innerFunc(arg))
}
//example:
//SINGLE ARGUMENT CASE
const multiplyBy2 = num => num * 2;
const cachedMultiplyBy2 = fastCache(multiplyBy2);
If you want a simple cache function:
function cacheWrapper(fn) {
let cache = { };
return arg => {
if (cache.hasOwnProperty(arg)) {
return cache[arg];
}
return cache[arg] = fn(arg);
};
}
function test(x) {
return x * 2;
}
let testCached = cacheWrapper(test);
console.log(testCached(2));
console.log(testCached(2));
The key here is hasOwnProperty which will tell you if that cache slot is occupied or not. This avoids having to fumble around and find out the hard way with iteration.
If the number isn't already in the object, it won't be found in the loop.
function fastCache(func) {
const obj = {};
function innerFunc(arg) {
for (const key in obj) {
if (key === arg) {
return obj[arg]
}
}
obj[arg] = func(arg)
return func(arg)
}
return innerFunc
// console.log(innerFunc(arg))
}
//example:
//SINGLE ARGUMENT CASE
const multiplyBy2 = num => num * 2;
const cachedMultiplyBy2 = fastCache(multiplyBy2);
const result = cachedMultiplyBy2(8);

Apparently simple function not returning anything

I'm sure I'm just having a moment, but I can't figure this out for anything. I wanted to create a quick function to sum up a particular JSON object's values over an array, but it returns nothing. Here's the code:
var a=[{"b":"23"},{"b":"37"}]
function sumJSON(json,elem){
var total=0;
$.each(json,function(index,item){
var count=index+1;
total+=Number(item[elem]);
if(count===json.length){
return total;
}
})
}
console.log(sumJSON(a,"b"));
Here's the jsfiddle
Just in case you want this to be solved with plain javascript.
var a = [{"b":"23"},{"b":"37"}]
function sumJSON(a,key) {
return a.reduce((s, data) => s + (+data[key]), 0)
}
console.log(sumJSON(a, 'b'))
var a=[{"b":"23"},{"b":"37"}]
function sumJSON(json,elem){
var total=0;
$.each(json,function(index,item){
total+=Number(item[elem]);
})
return total;
}
console.log(sumJSON(a,"b"));
$each needs not to return anything, just calls a function for each member of the collection, you need to return the total after the call to $.each, once the function has been called for all the elements

Javascript function not returning false

This function is only returning true. I have added a console.log in the if block and it is called but the function doesn't return false.
function isUniform(List)
{
var ele = List[0];
List.forEach(function(item)
{
console.log(ele);
if(ele !== item)
{
return false;
}
})
return true;
}
You need another method for testing unifomity. Better use Array#every, which checks every value with the first item of the array and return true, if all elements are equal and false if not. The iteration stops with the first unequal element.
function isUniform(list) {
return list.every(function(item, _, array) {
return item === array[0];
});
}
The used Array#forEach returns always undefined:
forEach() executes the callback function once for each array element; unlike map() or reduce() it always returns the value undefined and is not chainable.
I think you can use this code;
function isUniform(List)
{
var res = true;
var ele = List[0];
List.forEach(function(item)
{
console.log(ele);
if(ele !== item)
{
res = false;
return;
}
})
return res;
}

Get index in an array.filter callback function

I have the following array filter with a callback function:
array.filter(createPredicateFn(expression, comparator));
My call back function is declared as follow:
function createPredicateFn(expression, comparator) {
How can I get the index of the element inside my createPredicateFn?
Edit:
here is my predicate function:
function createPredicateFn(expression, comparator) {
var predicateFn;
if (comparator === true) {
comparator = angular.equals;
} else if (!angular.isFunction(comparator)) {
comparator = function (actual, expected) {
if (angular.isObject(actual) || angular.isObject(expected)) {
// Prevent an object to be considered equal to a string like `'[object'`
return false;
}
actual = angular.lowercase('' + actual);
expected = angular.lowercase('' + expected);
return actual.indexOf(expected) !== -1;
};
}
predicateFn = function (item) {
return deepCompare(item, expression, comparator);
};
}
Within your createPredicateFn() you have to return another function. This inner function can have up to three parameters:
the value of the element
the index of the element
the Array object being traversed
(Source: MDN)
Hence the second parameter of your inner function is the index you look for.
A simplistic example could look like this:
function createPredicateFn(expression, comparator) {
return function( val, index, arr ) {
// do something and return a boolean here
return index % 2 == 0;
}
}

Javascript function call with another function as parameter

I have a few functions in two different files that are all linked together by function calls they are as follows
FILE 1:
function getFunction(func){
}
FILE 2:
function Numbers(one, two) {
return (one*two);
}
var func = getFunction(Numbers);
and these are called by:
func(input_array);
my array has values 1,3,5,7,9 and I need func(input_array) to return 3,15,35,63,9 (the last value loops back to the first value)
basically what I am trying to do is have getFunction return a function such that these values are calculated. I am having trouble because I can't wrap my mind about sending and returning functions. I don't know how to access the array if it isn't sent into the function. Let me know if I need to clarify anything.
function getFunction(callback) {
return function(array) {
return array.map(function(cur, index) {
return callback(cur, array[(index+1) % array.length]);
});
};
}
getFunction returns a closure over the callback parameter, which is the function that you want to call. The closure receives the array parameter, and it calls the callback in a loop over the array using array.map. The % modulus operator performs the wraparound that you want.
Another way to write this that may be clearer is:
function getFunction(callback) {
return function(array) {
var result = [];
for (var i = 0; i < array.length; i++) {
j = (i+1) % array.length; // Next index, wrapping around
result.push(callback(array[i], array[j]));
}
return result;
};
}
var func = getFunction(Numbers);
console.log(func([1,3,5,7,9])); // Logs [3,15,35,63,9]
here is simple function that returns what you need
function Numbers(x) {
output_array=[];
for(i=0;i<x.length;i++){
if(x[i+1]==undefined){
output_array.push(x[i]);
}
else{
output_array.push(x[i]*x[i+1]);
}
}
return output_array;
}
var input_array=[1,3,5,7];
var num = Numbers(input_array);
console.log(num);
OR if you need it in the way function calling another function
and than returning the result use this
function getFunction(Numbers,input_array){
return Numbers(input_array);
}
function Numbers(x) {
output_array=[];
for(i=0;i<x.length;i++){
if(x[i+1]==undefined){
output_array.push(x[i]);
}
else{
output_array.push(x[i]*x[i+1]);
}
}
return output_array;
}
var input_array=[1,3,5,7];
var num = getFunction(Numbers,input_array);
console.log(num);

Categories