Array summing method not working // javascript [closed] - javascript

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I'm trying to sum (ie. 4+15+10 etc... = total) the below array. I believe I'm using the right code but it doesn't seem to be working. Can someone take a look at it for me?
function beginhere() {
var arr = [4,15,10,7,6,18,1,18,8,45,55,16,9,19,11,13,14];
var total =0
var i =0
for(i < arr.length; i++) {
total += arr[i][1];
}
document.getElementById("thismessage").innerHTML = i;
}

You need just the element, without another index, because you have an array with single values and not an array of arrays.
total += arr[i];
// ^^^
and the right start value for the for statement
for (i = 0; i < arr.length; i++) {
// ^^^^^
and you need to assign the total instead of the loop variable i.
document.getElementById("thismessage").innerHTML = total;
// ^^^^^
function beginhere() {
var arr = [4, 15, 10, 7, 6, 18, 1, 18, 8, 45, 55, 16, 9, 19, 11, 13, 14],
total = 0,
i;
for (i = 0; i < arr.length; i++) {
total += arr[i];
}
document.getElementById("thismessage").innerHTML = total;
}
beginhere();
<div id="thismessage"></id>

For loop syntax was wrong.its a for(i=0; i<length; i++)
Second problem was addition with array arguments. total += arr[i];
last one the you are not print the total value.you just print the increment .but the not use because is outside loop
function beginhere() {
var arr = [4,15,10,7,6,18,1,18,8,45,55,16,9,19,11,13,14];
var total =0
var i =0
for(i=0; i < arr.length; i++) {
total += arr[i];
}
console.log(total);
}
beginhere();
Another method Array#reduce Arrow function simply use like this
var arr = [4,15,10,7,6,18,1,18,8,45,55,16,9,19,11,13,14];
var res = arr.reduce((a,b) => a+b ,0)
console.log(res)

A few corrections:
You are missing a semicolon at the beginning of your for loop;
You don't need the extra [1] after your arr[i] access; and
You probably meant to set your content to total instead of i.
A few other suggestions:
Use textContent instead of innerHTML when you don't plan on inserting tags; and
Place var i = 0 inside of your for loop (this is common practice).
function beginhere() {
var arr = [4, 15, 10, 7, 6, 18, 1, 18, 8, 45, 55, 16, 9, 19, 11, 13, 14]
var total = 0
for (var i = 0; i < arr.length; i++) {
total += arr[i]
}
document.getElementById("thismessage").textContent = total
}
beginhere()
<p id="thismessage"></p>

Related

Check for multiple numbers in an array [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I need to create a function that checks all numbers in an array and print them out.
My idea was something similar to this:
var array = [15,22,88,65,79,19,93,15,90,38,77,10,22,90,99];
var string = "";
var len = array.length;
After declaring the variables, i start to loop them:
for (var i = 0; i < len; i ++) {
for (var j = 0; j < len; j ++) {
//console.log(array[i], array[j]);
}
}
Console prints me value in this order:
3 3
3 6
3 67
. .
6 3
6 6
6 67
. .
I thought to create a if statement checking if array[i] is equal to array[j] then pushing the content in a new string.
You need to iterate in the outer loop until the element before the last item and in the inner loop start from the actual index plus one, to prevent to check the same element.
If duplicate is found, push the value to the duplicates array.
var array = [15, 22, 88, 65, 79, 19, 93, 15, 90, 38, 77, 10, 22, 90, 99],
len = array.length,
i, j,
duplicates = [];
for (i = 0; i < len - 1; i++) {
for (j = i + 1; j < len; j++) {
if (array[i] === array[j]) duplicates.push(array[i]);
}
}
console.log(duplicates);
A shorter approach by using a Set
var array = [15, 22, 88, 65, 79, 19, 93, 15, 90, 38, 77, 10, 22, 90, 99],
found = new Set,
duplicates = array.filter(v => found.has(v) || !found.add(v));
console.log(duplicates);
You can also use Set with Array.filter and Array.indexOf:
let data = [15,22,88,65,79,19,93,15,90,38,77,10,22,90,99]
let r = new Set(data.filter((v, i, a) => a.indexOf(v) !== i))
console.log(Array.from(r))
The idea is to filter the items to those who have multiple indexes found and then add them to the Set. Since Set stores unique items only it will take care of the duplicates and you get the final result.
We take advantage of the fact that Array.filter provides 3 arguments to the iteratee function - value (v), current index (i) and the actual array (a).

Javascript Array - showing the index of the lowest number

Complete JS newbie here!
I made an Array with a few numbers in it. I added a function that will show me the lowest number. My question can I show the index of the lowest number?(even If I would change the numbers)
Here is my code in case you need it:
function func()
{
var low= 0;
var numbersArr=[29, 26, 44, 80, 12, 15, 40];
for(var i = 0; i <= numbersArr.length;i++)
{
if(numbersArr[i]< numbersArr[i-1])
{
low = numbersArr[i];
}
}
console.log(low);
}
func();
You can also store value of i in one variable. See below code.
function func()
{
var numbersArr=[29, 26, 11, 44, 80, 12, 15, 40,10];
var low = numbersArr[0];
var indexOfLow;
for(var i = 0; i <= numbersArr.length;i++)
{
if(numbersArr[i]< low)
{
low = numbersArr[i];
indexOfLow = i;
}
}
console.log("Lowest number is : "+low);
console.log("Index of lowest number is : "+indexOfLow);
}
func();
My question can I show the index of the lowest number?
You can do
numbersArr.indexOf(low)
Edit
That said, your logic of finding the lowest number isn't correct as you are only comparing the consecutive values of the array, try the updated logic in demo below.
Demo
function func() {
var numbersArr = [29, 26, 11, 44, 80, 12, 15, 40];
var low = numbersArr[0];
for (var i = 1; i <= numbersArr.length; i++) {
if (numbersArr[i] < low ) {
low = numbersArr[i];
}
}
console.log(low);
console.log(numbersArr.indexOf(low));
}
func();
You function lack the problem of keeping the lowest value, because you compare only the actual element and the element before.
function getLowestValue(array) {
var low = 0,
i;
for (i = 0; i < array.length; i++) { // just loop i < array.length!
if (array[i] < array[i - 1]) {
// ^^^^^^^^^^^^ this is the problem, you need to check against low
low = array[i];
}
}
return low;
}
console.log(getLowestValue([29, 26, 11, 80, 12, 15, 40])); // 12 instead of 11
You could store the value of the lowest element and compare with this value.
function getLowestValue(array) {
var low = array[0], // take the first element at index 0
i;
for (i = 1; i < array.length; i++) { // start with index 1, because you need to
// check against the last known smallest value
if(array[i] < low) {
low = array[i];
}
}
return low;
}
console.log(getLowestValue([29, 26, 11, 80, 12, 15, 40])); // 11 the right value
For getting the lowest index, you could just store the index instead of th value and take it for comparison.
function getLowestIndex(array) {
var lowIndex = 0,
i;
for (i = 1; i < array.length; i++) {
if (array[i] < array[lowIndex]) {
lowIndex = i;
}
}
return lowIndex;
}
console.log(getLowestIndex([29, 26, 11, 80, 12, 15, 40])); // 2
No need to make a function to find minimum value. You can use simply Math.min.apply to find minimum value from array and then indexOf to find index of that value
var numbersArr = [29, 26, 44, 80, 12, 15, 40];
var minValue = Math.min.apply(null, numbersArr);
console.log("Minimum Value:"+ minValue, "Index is:" + numbersArr.indexOf(minValue));
Solution:You will declair a variable which will hold the index of low number and assign it in the if statement as shown below:
if(numbersArr[i]< numbersArr[i-1])
{
low = numbersArr[i];
IndexLow=i;
}
I found a super easy way to do that, in your way. Just little change in your code. Please take a look.
function func()
{
var numbersArr=[29, 31, 26, 44, 80, 123, 151, 40,15];
var low= numbersArr[0];
var index = 0;
for(var i = 1; i < numbersArr.length;i++)
{
if(low >= numbersArr[i])
{
low = numbersArr[i];
index = i;
}
}
console.log(index);
console.log(low);
}
func();
Hope you found your problem. Happy coding :)

Every n times, skip n items and increase n by 1

This is probably an odd question since I have a solution (below), but was hoping someone could show me a more succinct or readable way to do this:
I created a loop that outputs the following array:
[0, 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, 66, 78, 91]
the gaps between numbers get progressively larger:
1-0 = 1
3-1 = 2
6-3 = 3
10-6 = 4
...
91-78 = 13
etc.
I did it by creating two variables, step keeps track of the gap size and count keeps track of the current 'position' in the gap. count counts down to zero, then increases step by one.
var output = [];
var step = 0;
var count = 0;
for (var i = 0; i < 100; i++) {
if (count == 0){
step += 1;
count = step;
output.push(i);
}
count -= 1;
}
You can try the following:
var output = [];
var total = 0;
for (var i=1; i < 100; i++) {
output.push(total);
total += i;
}
The gaps between numbers simply increase by one for each step, so a for loop should be able to track this change.
You should skip useless iterations. If you want a sequence of 100 numbers, use
var output = [];
var step = 0;
for (var i = 0; i < 100; i++) {
step += i;
output.push(step);
}
If you want the general term,
aₙ = ∑ⁿᵢ₌₀ i = n*(n+1)/2
So you can also do
var output = [];
for (var i = 0; i < 100; i++) {
output.push(i * (i+1) / 2);
}
You can save the total helper variable with this solution:
var output = [0]
for (var i = 1; i < 14; i++) {
output.push(output[i - 1] + i)
}
console.log(output) // [ 0, 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, 66, 78, 91 ]
This solution takes into account that the value to add the counter value to is already present at the last position in the array.
A recursive version is also possible:
output = (function f(x) {
return x.length == 14 ? x : f(x.concat([x[x.length - 1] + x.length]))
})([0])
console.log(output); // [ 0, 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, 66, 78, 91 ]
Here is no additional counter variable is needed. I use concat because it returns an array what I need for the recursive call, where push returns the new array length. The argument for concat is an array with one element with the new value to add.
Try online

How to place the results of an if statement into a new array which I can return later

I'm fairly new to code and I've been stuck on one particular problem for quite some time. I feel I have a good grasp on what's needed for the problem, but can't figure out for the life of me how to return the results of a if statement into a new array which I can then return. Any help or advice would be greatly appreciated.
function loveTheThrees (myArray) {
var myTotal = 0;
for (var i = 0; i < myArray.length; i++) {
if (myArray[i] % 3 === 0) {
myTotal += myArray[i];
/* What I'm looking to do at this stage of the problem is place the results into a new array which will be returned rather than myTotal */
}
}
return myTotal; // Placed this here just to test to see if the problem would post the results
}
loveTheThrees ([1, 3, 5, 12, 21]);
You could use Array#filter for it.
function loveTheThrees(myArray) {
return myArray.filter(function (a) {
return a % 3 === 0;
});
}
console.log(loveTheThrees([1, 3, 5, 12, 21]));
Try this:
function loveTheThrees (myArray) {
var newarray = []
for (var i = 0; i < myArray.length; i++) {
if (myArray[i] % 3 === 0) {
newarray[newarray.length] = myArray[i]
}
}
return newarray;
}
loveTheThrees ([1, 3, 5, 12, 21]);
Does that answer your question? It takes any item with no remainder when divided by three (%3) and puts it into the array newarray, and returns it.
With an arrow function expression :
var loveTheThrees = (myArray) => myArray.filter(element => element % 3 === 0);
console.log(loveTheThrees([1, 3, 5, 12, 21]));

Need an array where with first element of new array=sum of all elements except the first element-Javascript [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Improve this question
I have an array arr[0,1,2,3,..10] in Java script.I need to make a new array with first element of new array=sum of all elements except the first element of the previous array,and goes on.
Description: I have
Array=new Arr[0,1,2,3,..10].
I need an
Array=new new Array[first element,second element..]
where
first element=(1+2+..10)-0 ,
second element=(0+2+3+..10)-1,
third element=(0+1+3+..10)-2,
.. goes on till last element.
var myArray = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var sum = myArray.reduce(function(previous, current) {
return previous + current;
}, 0);
var newArray = myArray.map(function(currentElement) {
return sum - currentElement;
});
console.log(newArray);
Output
[ 55, 54, 53, 52, 51, 50, 49, 48, 47, 46, 45 ]
Algorithm goes like this
Just calculate the sum of all elements in the array
Traverse the array and reduce the element value from the sum and push into new array
Code
var sum = 0;
var result = [];
for (var i = 0; i < arr.length; i++) {
sum += arr[i];
}
for (var i = 0; i < arr.length; i++) {
result.push(sum - arr[i]);
}
console.log(result);
Note that, this can be done with short snippets of code as well using a combination of Array.reduce and Array.every, Array.slice. But these all methods have browser compatibility issues as they are not supported in older IE browsers.
It looks like you'll have to do something like this:
var nums = new Array(0,1,2,3,4,5,6,7,8,9,10);
var sum = Function('return ' + nums.join('+') + ';')();
var final = [];
for(j = 0; j < nums.length; j++){
final.push(sum - (2 * nums[j]) );
}
console.log(final);
The reason you have to do (2 * nums[i]) in the last step is:
To get rid of the item from the original addition (the 2 in the line below - from your code),
To subtract it at the end of the line.
var third element=(0+1+3+..10)-2,
fiddle
- Cred to #wared for the sum function -
You can do this:
arr = [0,1,2,3,4,5,6,7,8,9,10]
//Sum them all
sum = 0
for(i=0; i<arr.length; i++){
sum+=arr[i];
}
//Calculate the result
result = []
for(i=0; i<arr.length; i++){
result.push(sum-arr[i]);
}
alert(result);
Check this fiddle: http://jsfiddle.net/eg7F6/
This is the generic approach:
var array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var sum = array.reduce(function (sum, value) { return sum+= value });
var newArray = array.map(function(value) { return sum - value });
However, if the array has always values from 0 to 10, you could do some shortcut – but at this point, I do not understand the point of having that.

Categories

Resources