Apparently simple function not returning anything - javascript

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

Related

Undefined array parameter with 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;
})
}

Having a difficult time understanding callback functions

I'm new to JavaScript and i'm having difficulties understanding callback functions.
I have a function below that returns an array and then another function that calls the first function. Problem is, the array in the second function is always undefined, even though in the first function is returns an array of objects.
function getItems() {
$.get(url,
function(data) {
var obj = $.parseJSON(data);
var itemArr = $.map(obj, function(ele) { return ele; })
return itemArr;
});
}
function alertTest() {
var items = getItems();
alert(items);
}
I understand that the first function is asynchronous and so that the alert in the second function is called before the returned array, which causes the second function to alert an undefined object.
I'm aware there is quite some documentation around this but i'm having trouble understanding how it works. Could someone show me the changes i would need to make so that the alertTest function returns the populated array after the getItems function has been called?
Thanks in advance!
$.get is an async function. which means the callback function is invoked when the is hit and the response is returned inside .
Now return itemArr is actually returned by the callback function and
getItems() doesn't actually return anything and hence it is always undefined.
For your code to work,
function getItems() {
$.get(url,
function(data) {
var obj = $.parseJSON(data);
var itemArr = $.map(obj, function(ele) { return ele; })
alertTest(itemArr);
return itemArr;
});
}
this would call alertTest function.
One way to do this would be to use JS Promises like so
function getItems() {
return Promise.resolve(
$.get(url,
function (data) {
var obj = $.parseJSON(data);
var itemArr = $.map(obj, function (ele) {
return ele;
})
return itemArr;
}));
}
function alertTest() {
var items = getItems().then(function (items) {
alert(items);
});
}
It is a hard one to get your head around. Promises allow you to write code that runs in a sequence like sync code.
You could insert callbacks into the function and have that call when the get request finishes like shown in the other answer by Rhea but this is a cleaner way to do this and Promises are now part of the Javascript language.
function getItems() {
$.get(url, function(data) {
var obj = $.parseJSON(data);
var itemArr = $.map(obj, function(ele) { return ele; })
alertTest(itemArr);
});
}
function alertTest(items) {
alert(items);
}
getItems();

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);

How argument is being passed in the function(which itself is an argument) in JavaScript

I have a very basic question about JavaScript.
Consider the following code:
var numbers = [4,2,3,4,5,4,3,2,1];
var everyResult = numbers.every(function(item,index,array) {
alert(arguments.length);
return (item > 1);
});
Now in the above code I am passing anonymous function as an argument of "every" function.
How exactly my anonymous function is getting the exactly 3 arguments(item,index,array).
This isn't really a basic javascript question, but a library question, and how it "happens" depends on the implementation.
This here is a sample implementation of every in javascript:
function every(array, fn) {
for(var i = 0; i < array.length; i++) {
fn(array[i], i, array);
}
}
You would call it like this:
every([1,2,3,4], function(item, index, array) {
// do stuff
});
As you can see, it's the every function itself, that calls the fn (which is the function you pass in), and decides what arguments to pass.
The anonymous function you're passing is simply provided as argument for every() method which calls it for a number of times. every() iterates through your list items and calls your anonymous function each time with three arguments: value, index and your entire array.
Here's an approximate source code of how the actual every() function works:
Array.prototype.every = function(callback) {
for(i=0; i<this.length; i++) {
callback(this[i], i, this);
}
}
Let's build a simple function with a callback argument:
function foo(callback)
{
var callbackArgument = 'bar';
callback(callbackArgument);
}
Let's use it:
foo(function(arg){
console.log(arg);
}); // logs "bar" to the console!
How exactly my anonymous function is getting the exactly 3
arguments(item,index,array)?
Maybe it would be easier to understand with an alternative example You have:
var numbers = [4,2,3,4,5,4,3,2,1];
var everyResult = numbers.every(function(item,index,array) {
alert(arguments.length);
return (item > 1);
});
You could also write the same in the following manner:
var numbers = [4,2,3,4,5,4,3,2,1];
var everyResult = numbers.every(item,index,array) {
function anonymous(firstVar,secondVar,thirdVar){
//do your anonymous stuff here
alert(thirdVar.length);
return (firstVar > 1);
}
//get the anonymous function processed data
var anonymousFunctionResults = anonymous(item,index,array);
//do your original stuff that you would have done with the results of anonymous function
anonymousFunctionResults...
}
});
Or in this way:
function anonymous(firstVar,secondVar,thirdVar){
//do your anonymous stuff here
alert(thirdVar.length);
return (firstVar > 1);
}
var numbers = [4,2,3,4,5,4,3,2,1];
var everyResult = numbers.every(item,index,array, anonymous) {
//get the anonymous function processed data
var anonymousFunctionResults = anonymous(item,index,array);
//do your original stuff that you would have done with the results of anonymous function
anonymousFunctionResults...
}
});
Or in this way:
function anonymous(firstVar,secondVar,thirdVar){
//do your anonymous stuff here
alert(thirdVar.length);
return (firstVar > 1);
}
var numbers = [4,2,3,4,5,4,3,2,1];
var everyResult = numbers.every(anonymous(item,index,array)) {
//get the anonymous function processed data
//you can use the "firstParameter" variable already of course
//this is just to make a point
var anonymousFunctionResults = firstParameter;
//do your original stuff that you would have done with the results of anonymous function
anonymousFunctionResults...
}
});
If I understood your question well :)

how to return/pass value from javascript function?

A rather trivial question, how do I return or pass a value outside the function?
Code below:
function numberOfDivs(){
var numberOfElements = $("#div").children().length; //this count how many divs exist
return numberOfElements;
}
$("#element").click(function(){
numberOfDivs();
console.log(numberOfElements);// here I need to return the number but getting error :(
});
many thanks
$("#element").click(function(){
var numberOfElements= numberOfDivs();
console.log(numberOfElements);
});
Try
var numberOfElements= numberOfDivs();
console.log(numberOfElements);
As the function is to return a value, while we invoke the function we assigned a variable to capture the result
var numberOfElements;
function numberOfDivs(){
numberOfElements = $("#div").children().length; //this count how many divs exist
}
$("#element").click(function(){
console.log(numberOfElements);// here I need to return the number but getting error :(
});
One way is : define numberOfElements in global scope like this :
var numberOfElements;
function numberOfDivs(){
numberOfElements = $("#div").children().length; //this count how many divs exist
return numberOfElements;
}
$("#element").click(function(){
numberOfDivs();
console.log(numberOfElements);// here I need to return the number but getting error :(
});
Or another way is : assign the result in one variable and use that
$("#element").click(function(){
var output = numberOfDivs();
console.log(output);// here I need to return the number but getting error :(
});
Try using Callback functions, consider a scenario where incase your numberofDivs function takes time to return the value, it will not give the appropriate results as Jquery is an asynchronous. See this demo for the use of callback to return the data CALLBACK DEMO
function AppendJson(callback) {
var numberOfElements = "AppendJson";
callback(numberOfElements)
}
AppendJson(function (ReturnValue) {
alert(ReturnValue);
});

Categories