I have two functions that should produce the same result. I would like clarification as to why they do not. I'm not grasping the significant difference that must exist between for-loop and .forEach.
I'd like to though :)
//
//DEMO OBJECT WITH TWO ARRAYS
//
var myArray = {
myList1 : [1,2,3,4],
myList2 : [5,6,7,8]
}
//
//FUNCTION ONE: Produces the sum of myArray.myList1 as expected.
//
var firstWay = function(){
var sum = 0;
for(var i = 0; i < myArray.myList2.length; i++){
sum += myArray.myList2[i];
}
return sum
};
var results2 = firstWay();
console.log(results2);
//FUNCTION TWO PRODUCES NaN
//1.) I don't know why it produced NaN.
//2.) I don't understand why this function wouldn't produce the same result as firstWay.
var secondWay = function() {
var sum = 0;
myArray.myList1.forEach(function(cur){
sum += cur.value;
});
return sum;
};
var results1 = secondWay();
console.log(results1);
Remove value from sum += cur.value so it's just sum += cur. The value
you need is already contained in cur.
var secondWay = function() {
var sum = 0;
myArray.myList1.forEach(function(cur){
sum += cur;
});
return sum;
};
var results1 = secondWay();
console.log(results1);
Many answers just stand in the doc and might be found by googling.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
callback
Function to execute on each element. It accepts between one and three arguments:
currentValue
The current element being processed in the array
index Optional
The index currentValue in the array
array Optional.
The array forEach() was called upon "
So cur in your code is the current element of your array of integers. So it's an integer. So it has no value property, it IS the value you're looking for, as pointed out in a comment.
On the second iteration you wrongly put sum += cur.value.
The right way shoud be : sum += cur.
Related
I am having a huge issue with a coding problem I need to make. I am being asked to run a sum of numbers inside of an array and I can't get the code to run properly.
This is my code and below are the instructions of what I am being asked to run:
function sumOfRange(numbers){
var numbers = [1,-1,1,-1,1];
var sum = 0;
for (var i = 0; i < numbers.length; i++){
sum += numbers[i];
}
return sum;
}
// Your Challenge:
// - Create a function named sumOfRange.
// - It accepts one parameter, called numbers, that
// represents an array of numbers.
//
// - In your function, sum the numbers inside the array.
// (Reminder: you'll need a variable to store the result.)
// - Return the result.
// Hint: You do not need to create a new array - you will be
// looping through the parameter, which is already coming in as
// an array.
// Someone else will be calling your function like this:
// sumOfRange([1,2,3,4,5])
// sumOfRange([-4,-5,-10,0])
I keep getting
errors saying
You returned '1'. That isn't quite right. The sum of [1,2,3,4,5] is 15.
Any help with this would greatly appreciate it.
Remove the first line of your function sumOfRange() var numbers = [1,-1,1,-1,1] because you are re-initializing the value of numbers, you need to use to array that is passed to the function when it is called.
function sumOfRange(numbers) {
var sum = 0;
for (var i = 0; i < numbers.length; i++) {
sum += numbers[i];
}
return sum;
}
console.log(sumOfRange([1,-1,1,-1,1]));
console.log(sumOfRange([1,2,3,4,5]));
console.log(sumOfRange([-4,-5,-10,0]));
var a = [1,2,3,4,5];
function sum (arr) {
return arr.reduce(function(prev, curr) {
return prev + curr;
}, 0);
}
//sum(a) -> returns 15
I am attempting to write a function that takes an (unsigned) integer as input, and returns the number of bits that are equal to one in the binary representation of that number.
Example: The binary representation of 1234 is 10011010010, so the function should return 5 in this case.
Here is my answer:
var newArr;
var count = 0;
function countBits(num){
newArr = num.toString(2).split('').map(function(el){
if(el == '1')
count++
});;
return count;
}
In my program when I call countBits(7) it returns //3 but when I submit my response it says it is returning //4. Can someone see what I am missing in my response based on question?
Your problem is that you are declaring the variables outside of the function, so when the function is called multiple times they'll keep their values and just increase the count.
Btw, you also shouldn't use map if you don't want to create another array - so better do
function countBits(num){
var newArr = num.toString(2).split('').map(Number);
var count = 0;
for (var i=0; i<newArr.length; i++)
count += newArr[i];
}
return count;
}
or
function countBits(num){
return num.toString(2).split('').reduce(function(count, el) {
return count + (el == "1");
}, 0);
}
function countBits(num){
/* Convert num Base10 to num Base2
then find Ones and save them in an array
length of the array is equal their sum */
return num.toString(2).match(/1/g).length
}
function countBits(num){
// convert num Base10 to Base2
let base2 = num.toString(2)
// declare variable for sum of bits
let sum = 0
// for loop to check bits (bit = 1) and ignore Zeros in the String base2
for(let i = 0; i < base2.length; i++){
if(base2[i] == 1){
// use Number() to convert string to number
count += Number(base2[i])
}
}
return sum ;
}
I have the following JSON array:
fruits = [{"fruit":"banana","amount":"2","price":"1"},{"fruit":"apple","amount":"5","price":"2"},{"fruit":"kiwi","amount":"1","price":"5"}]
How can I calculate all the "price" values together? The result should be 8.
I have so far the following but problems accessing the price items:
function count(fruits) {
var sum = 0;
for (var i = 0; i < fruits.length; i++) {
sum = sum + fruits[i][price];
}
return sum;
}
console.log(count(fruits)
Thank you!
You need to access them like:
fruits[i].price
and then convert them to numbers before adding them:
parseInt(fruits[i].price, 10);
Final code:
fruits = [{"fruit":"banana","amount":"2","price":"1"},{"fruit":"apple","amount":"5","price":"2"},{"fruit":"kiwi","amount":"1","price":"5"}]
var total = 0;
for(var i=0; i<fruits.length; i++){
total += parseInt(fruits[i].price, 10);
}
alert(total); //8
See the DEMO here
Two things:
The line
sum = sum + fruits[i][price];
should be
sum = sum + fruits[i].price;
or even
sum += fruits[i].price;
Your code was trying to use a variable called price, not the price property of the fruit entry.
Your prices are strings, so we want to make sure they're converted to numbers when summing them up. You have lots of options there: Apply a unary + to them, pass them into Number(), or use parseInt(..., 10). Below I'll go with a unary +, but there are pluses (no pun!) and minuses to each.
var fruits = [{"fruit":"banana","amount":"2","price":"1"},{"fruit":"apple","amount":"5","price":"2"},{"fruit":"kiwi","amount":"1","price":"5"}]
function count(fruits) {
var sum = 0;
for (var i = 0; i < fruits.length; i++) {
sum += +fruits[i].price; // <=== change is here
}
return sum;
}
display(count(fruits));
function display(msg) {
var p = document.createElement('p');
p.innerHTML = String(msg);
document.body.appendChild(p);
}
With ES5's array additions (which can be shimmed on older browsers), you can do this with either forEach or reduce:
forEach:
var fruits = [{"fruit":"banana","amount":"2","price":"1"},{"fruit":"apple","amount":"5","price":"2"},{"fruit":"kiwi","amount":"1","price":"5"}]
function count(fruits) {
var sum = 0;
fruits.forEach(function(fruit) {
sum += +fruit.price;
});
return sum;
}
display(count(fruits));
function display(msg) {
var p = document.createElement('p');
p.innerHTML = String(msg);
document.body.appendChild(p);
}
reduce:
var fruits = [{"fruit":"banana","amount":"2","price":"1"},{"fruit":"apple","amount":"5","price":"2"},{"fruit":"kiwi","amount":"1","price":"5"}]
function count(fruits) {
var sum = 0;
sum = fruits.reduce(function(prev, fruit) {
return prev + +fruit.price;
}, 0);
return sum;
}
display(count(fruits));
function display(msg) {
var p = document.createElement('p');
p.innerHTML = String(msg);
document.body.appendChild(p);
}
Your code has 2 errors:
To access the price property
fruits[i][price]
should be
fruits[i]['price'] or fruits[i].price
The price property is of type string. So the '+' operator will concatenate the price strings. To add them together you need to change their type to number by doing
parseInt(fruits[i]['price'], 10) or +fruits[i]['price']
If the price property doesn't contain a valid number the result will be NaN (not a number). You could avoid that by using the or operator.
+fruits[i]['price'] || 0
Using the ES5 Array extensions supported by all modern browsers you could write
fruits.reduce(function(m,v) { return m + (+v.price);}, 0);
With ES6 in future browsers this could be reduced to
fruits.reduce((m,v) => m + (+v.price), 0);
You have some errors in your code.
The first one is here: sum = sum + fruits[i][price];
you are trying to use a variable called price, not the property price of the object. You can access to the property using fruits[i]["price"] or fruits[i].price.
To obtain a number, when you are doing the sum, you need to convert the strings in numbers, to do that you can use parseInt(fruits[i]["price"]);. Last error in the last line you forgot the parenthesis and semicolon.
JSFiddle
your function is OK, just add parseInt for it to convert to type int, and has a incorrect syntax in fruits[i][price].
You've two option:
fruits[i]["price"]
OR
fruits[i].price
In my opinion, I would add a small logic code to check if it's a number or not. and return 0 if input data is undefined or null.
var fruits = [{"fruit":"banana","amount":"2","price":"1"},{"fruit":"apple","amount":"5","price":"2"},{"fruit":"kiwi","amount":"1","price":"5"}]
function count(data) {
var sum = 0;
if(data === void 0 ) return 0; // no array input
data.forEach(function(fruit) {
console.log(fruit);
sum += parseInt(fruit.price || 0 ); // if price is undefined, null or NaN, return 0
})
return sum;
}
display(count(fruits));
function display(msg) {
var p = document.createElement('p');
p.innerHTML = String(msg);
document.body.appendChild(p);
}
You should try this simple code snippet.
You don't need jQuery to do this operation. Simple JS would do.
var sum = 0;
for(var item in fruits){
sum += ~~(fruits[item].price)
}
console.log(sum)
Cheers!
I am having a problem in writing a javascript for finding the sum of the first 10 natural numbers. I have written the code with a while function and it is working well:
var total = 0, count = 1;
while (count <= 10) {
total += count;
count += 1;
}
console.log(total);
I am now wondering how you can do this using a for loop, if it is possible. Any help?
var total = 0;
for (var i = 1; i <=10; i ++){
total += i;
}
console.log(total);
An alternative for loops in this case is - reduce.
Arrays have reduce method which usage looks like this:
[1,2,3,4].reduce(function(total, number) {
return total + number;
}, 0);
You pass in a function accepting a total and current number from array and return their sum.
Zero at the end is starting value.
Arrays also have forEach method which you can use to iterate through your array like this:
var sum = 0;
[1,2,3,4].forEach(function(number) {
sum += number;
});
PS: reduce in some languages has an alias - fold.
Yet another variant based on lukas.pukenis answer
Array.apply(null,Array(10)) // [undefined,undefined,undefined,undefined,undefined,undefined,undefined,undefined,undefined,undefined]
.map(function(_, index){
return index+1;
}) // [1,2,3,4,5,6,7,8,9,10]
.reduce(function(total,curr){
return total+curr
}); // 55
Im trying to get the total combined value of a set of numbers.
Im getting the numbers as the text in an element tag storing them in an array then adding them all together. My problem is that its not inserting the numbers into the array as pairs.. it adding them as single integers .what am doing wrong.
check the jsfiddle too see example
http://jsfiddle.net/Wd78j/
var z = $('.impressions').text();
var x = [];
for(var i = 0; i < z.length; i++){
x.push(parseInt(z[i]));
}
console.log(x);
var total = 0;
$.each(x,function() {
total += this;
});
$('#impressTotals').append("[Total:" +total + "]");
$('#array').append("[Array:"+x+"]");
When you get text, it's taking all the numbers and concatenating them into a string. The below takes each element one at a time and pushes it.
var x = [];
$('.impressions').each( function( ) {
var z = $(this).text();
x.push(parseInt(z, 10));
})
Of course, you could build the sum up inside that each function, but I did it like this to more closely mirror your code.
text() returns the concatenated text of all of your impressions elements, of which you're adding together each character.
You want to loop through each impressions element, and keep a running sum going. Something like this should work
var sum = 0;
$('.impressions').each(function(){
sum = sum + (+$(this).text());
});
Updated Fiddle
Or to keep your original structure (don't forget the radix parameter to parseInt):
var z = $('.impressions');
var x = [];
z.each(function(){
x.push(parseInt($(this).text(), 10));
});
console.log(x);
var total = 0;
$.each(x,function() {
total += this;
});
$('#impressTotals').append("[Total:" +total + "]");
$('#array').append("[Array:"+x+"]");
Updated fiddle
You are iterating over a string, you could just use $.map to build the array instead, if you need it, otherwise just iterate and sum up the values :
var x = $.map($('.impressions'), function(el,i) {return parseInt($(el).text(), 10);}),
total = 0,
n = x.length;
while(n--) total += x[n] || 0;
$('#impressTotals').append("[Total:" +total + "]");
$('#array').append("[Array:"+x+"]");
FIDDLE