Add sums of array. Display one output - javascript

Update: The answer to this question is bellow. Thanks to dougtesting on a different thread. add array together, display sum
function hello() {
var arr = [];
for (var i = 0; i < 10; i++) {
arr.push(prompt('Enter number' + (i+1)));
}
var total = 0;
for(i=0; i<arr.length; i++) {
var number = parseInt(arr[i], 10);
total += number;
}
console.log(total);
}
//End of answer.
I am trying to have a user input 10 numbers. Then add those numbers together and display the output to the user. I was able to get the amount of inputs (10) into a array but I can't get arrays contents. I feel like I'm missing something simple. Would you mind taking a look?
// https://stackoverflow.com/questions/28252888/javascript-how-to-save-prompt-input-into-array
var arr = []; // define our array
for (var i = 0; i < 10; i++) { // loop 10 times
arr.push(prompt('Enter number' + (i+1))); // push the value into the array
}
alert('Full array: ' + arr.join(', ')); // alert the result
var arrEquals = []; //Empty Arr
arrEquals = arr.push(); //turn string into var
alert (arrEquals);//show string to admin for debug
//(for loop) console out # of array elements. does not output what is in array
//this is half the battle
for (var a = 0; a < arrEquals; a++){
var a = Number(a); //ensure input is Number()
console.log(a + "A"); //used for debug
}
//taks sums in array and adds them together
//this is the other half of the problem
// https://www.w3schools.com/jsref/jsref_forEach.asp
// var sum = 0;
// var numbers = [65, 44, 12, 4];
// function myFunction(item) {
// sum += item;
// demo.innerHTML = sum;
// }

This is probably one of the simplest examples of something that Javascript's built in array .reduce() function would be used for. Effectively, you're "reducing an array to a single value".
A reduce works by taking an array and running a function on each item. This "callback" function receives the value that the previous function returns, processes it in some way, then returns a new value. Worth noting, the reduce function also takes a 2nd argument that acts as the initial value that will be passed to the callback function the first time.
array.reduce(callbackFunction, initialValue);
Here's an example of reduce being used to sum an array.
var result = [1,2,3,4,5,6,7,8,9,10].reduce(function(accumulator, currentValue) {
return accumulator + currentValue;
}, 0); // start with an initial value of 0
console.log(result);
Using ES6 syntax, this can be further simplified to a one-liner
var result = [1,2,3,4,5,6,7,8,9,10].reduce((accumulator, currentValue) => accumulator + currentValue, 0);
console.log(result);

In your loop you're referencing arrEquals like for (var a = 0; a < arrEquals; a++){. you need to reference it like for (var a = 0; a < arrEquals.length; a++){ because just referencing the array doesn't tell javascript how long it is, or what number to count to. the .length returns a number, that number is how many items are in the array.

var arr = []; // define our array
for (var i = 0; i < 10; i++) { // loop 10 times
arr.push(prompt('Enter number' + (i+1))); // push the value into the array
}
arr = arr.join(', ');
alert('Full array: ' + arr); // alert the result
var arrEquals = []; //Empty array
arrEquals.push(arr); //assign arr string to an empty array
alert (arrEquals[0]); //show array[0] string to admin for debug
Is this what you are looking for? You need to put the arr.join() result to a variable, like itself.
You shouldnt be using arr.push() at all if you're not pushing new array items on it
//(for loop) console out # of array elements. does not output what is in array
//this is half the battle
for (var a = 0; a < arrEquals.length; a++){
//a is always a int in this case
console.log(a + "A"); //used for debug
}

Related

Working with a function that returns an array

I have written a function in Javascipt that returns a variable sized array. How do I declare/assign a variable in the calling function to accept this array and perform further processing on it?
function myArrayFunction()
{
const myArray = []; //Initialise Empty Array
var x = 0; //Array index (cannot use .push() function in my app)
for (let i = 0 ; i < 6 ; i++) {
myArray[x] = i * 2; //Simple function that doubles i and assigns value to index in array
}
return myArray; //Should return a 6 element array
}
const myOtherArray = []; //The array for the value returned from myArrayFunction() to be stored in
myOtherArray = myArrayFunction();
I get a warning the Debugging Scripts.array declaration error: invalid assignment to const `myOtherArray'. What's wrong?
I have tried using the const, let and var key words to initialise an empty array value.
I was expecting the variable that is passed out of the function would be assigned to the variable within the calling function.
Updated Code
Here is updated code, which includes a console.log statement enclosed in a second for loop. The result I expect is that the function should loop back through myArray and print out each of the elements at its 6 index locations.
function myArrayFunction()
{
const myArray = []; //Initialise Empty Array
var x = 0; //Array index (
for (let i = 0 ; i < 6 ; i++) {
myArray[x] = i * 2; //Simple function
}
for (i = 0; i < 6; i++) { //Loop through array
console.log(myArray[x]);
}
return myArray; //Should return a 6 element array
}
let myOtherArray = []; //The array to store returned array
myOtherArray = myArrayFunction();
console.log(myOtherArray);
When I run this code, I do not see an array of 6 numbers, but only the last one (10)
It seems that using the .push() function to create the array solves the problem
function myArrayFunction()
{
const myArray = []; //Initialise Empty Array
var x = 0; //Array index (cannot use .push() function in my app)
var y = 0; //The initial value of the array
for (let i = 0 ; i < 6 ; i++) {
y = i * 2;
myArray.push(y); //push the answer onto array
console.log("Value of myArray = " + myArray[i]);
}
return myArray; //Should return a 6 element array
}
It seems the error I am getting is not related to the Javascipt I had written, but rather the environment in which I am trying to execute it (Sparx Enterprise Architect). I will post on a more specialised forum and see if anyone has any ideas. Thanks all
You have a typo in the variable name of Session.Output(classiferIDArray[0]); causing the classiferIDArray is not defined error.
With your code updated, the output is a bunch of 10s because you're trying to use x as the index, but actually using i as the index in the for loop. I.e. x is always 0, and after the first for loop runs, the 0th entry in myArray is set to 5 * 2. Then you log that value a bunch of times in your next for loop.

Trying to create an array of duplicate values from another array, why doesn't my code work?

I am working on this piece of code here where the goal is to create an array of all the values that are duplicated from another array. The resulting array I'd like to have should only enter the duplicated values from the first array once. The catch is I can't use any array functions or methods. This is what I have so far:
var numbers = [8,24,20,5,13,3,1,12,11,24,8,24,20,4,5,23,24,23,21,2,19,3,21,2,14,17,21,5,7,10,20,11,0,5,18,2,13,11,14,3,20,1,23,6,21,10,14,0,15,20];
var results = [];
var tempArr = [];
for (var i = 0; i <= numbers.length; i++) {
if (tempArr[numbers[i]] === undefined) {
tempArr[numbers[i]] = 1;
} else if (results[numbers[i]] === undefined) {
results.push(numbers[i]);
}
}
console.log(tempArr);
console.log(results);
I am getting closer to me desired output… but for some reason the results array continues to contain multiple entries of the values that are duplicated in the numbers array. Where am I going wrong here?
You're basically abusing an array as an object. Try using an object instead to log your values (and give said object a name that represents what it holds), it'll greatly simplify your code:
var numbers = [8,24,20,5,13,3,1,12,11,24,8,24,20,4,5,23,24,23,21,2,19,3,21,2,14,17,21,5,7,10,20,11,0,5,18,2,13,11,14,3,20,1,23,6,21,10,14,0,15,20];
var results = [];
var seenValues = {};
for (var i = 0; i < numbers.length; i++) {
const number = numbers[i];
seenValues[number] = 1 + (seenValues[number] || 0);
// check to see if it's been seen exactly once before,
// so that the duplicated value is only added once:
if (seenValues[number] === 2) results[results.length] = number;
}
//console.log(seenValues);
console.log(results);

array.push produces different result than console.log for Heap's Algorithm in Javascript

I am trying to make an array of all the permutations for a given string using Heap's Algorithm. The function prints the correct array results when I use console.log to test. However, when I try to push all of the arrays into a new array it pushes the same initial array every time.
In this example it pushes [a, a, b] 6 times.
First of all, why is it doing this? Second, how do I get around it and push all of the correct results into my new array.
function permAlone(str) {
//make str into array
var arr = str.split('');
var allArrays = [];
//Heap's Algorithm to make new array with all permutations
var swap = function (array, pos1, pos2) {
var temp = array[pos1];
array[pos1] = array[pos2];
array[pos2] = temp;
};
var permute = function(array, n) {
n = n || array.length;
if (n === 1 ) {
console.log(array);
//allArrays.push(array);
}
else {
for (var i=1; i <= n; i += 1) {
permute(array, n-1);
if (n%2) {
var j=1;
}
else {
j=i;
}
swap(array, j-1, n-1);
}
}
};
permute(arr);
//console.log(allArrays);
}
permAlone('aab');
You only ever have one array (not counting allArrays), so you've pushed the same array into allArrays six times.
You should make a copy of your array before pushing it. You can do that with slice:
allArrays.push(array.slice(0));

Whats wrong with this piece of code?

Trying to figure out what's wrong with this piece of code.
//Code to return the sum of all values in an array
var x = [ 1,2,3,4,5 ];
//Function to return sum of values in an array
function sum(arr) {
var sum = 0;
for (i=1; i < arr.length; i++) {
sum = sum + x[i];
}
return sum;
}
What will be the value of sum(x)?
There's a couple issues here, some are worse than others
First of all you should delcare i as a variable, i=0 -> var i = 0
Then you need to start your for loop at 0 instead of 1 for(var i = 1 -> for(var i = 0 Arrays in javascript (and pretty much every other language) are 0-indexed. That means the first item is arrayName[0] not arrayName[1]
Then you were accessing your value in the array wrong you need to use arr[i] not x[i]. You want to access the value passed to the function, not the actual array you created before.
Line 8 can be shortened using += and was also missing a semicolon
//Code to return the sum of all values in an array
var x = [1, 2, 3, 4, 5];
//Function to return sum of values in an array
function sum(arr) {
var sum = 0;
for (var i = 0; i < arr.length; i++) {
sum += arr[i];
}
return sum;
}
console.log(sum(x)); //15 -- it works! (1+2+3+4+5=15)
As others have stated the issue is that arrays, and most other things in programming, are zero-indexed.
May I suggest an alternative stylistic choice...
var x = [ 1,2,3,4,5 ];
//Function to return sum of values in an array
var sum = function (arr) {
return arr.reduce(function(a,b){return a+b;})
}
console.log(sum(x));
Though, at this point the function is one line of code, and not really worth wrapping in a function. With things like that I simply do it inline.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
As #user6188402 mentions, i must start at 0.
Here's why:
var x = [ 1,2,3,4,5 ]; creates an array whose index starts at 0, so:
x[0] = 1
x[1] = 2
x[2] = 3
x[3] = 4
x[4] = 5
If you do sum = sum + x[i]; starting at 1, the answer will be 14 instead of 15

JavaScript function that produces an array that multiplies x number of times based on previous integer

So I've got this function and it needs to produce an array that multiplies x number of times based on previous integer. The function would take two integers as arguments as so:
function powerOf(x, n) {
}
For example: powerOf(3, 4) will produce [3, 9, 81, 6561].
Can someone point me in the right direction?
Here's a clean solution:
function powerOf(x, n) {
var res = [x];
for(var c=1; c<n; c++) {
res.push(x *= x);
}
return res;
}
alert(powerOf(3, 4));
This is the function you've been looking for:
function test(a,b){
// declarin array for result
var res = [a];
// going through array and adding multiplied numbers
for(var i = 1; i<b;i++){
res[i] = res[i-1]*res[i-1];
}
// returning the result
return res;
}
console.log(test(3,4)); // result : [3, 9, 81, 6561]
First you decalare array that will server you as result.First entry in array is your first number (a). Now for rest of array (b-1), you need to multiply last entry in array with it self.
function powerOf(x, n){
// First, create a results array to store your results in.
var resultsArr = [];
// Then create a variable to store your number.
var num;
// Iterate from 1 to n.
for (var i = 1; i <= n; i++) {
// If num is not yet defined, set it to x and push it to the array
if (!num) {
num = x;
resultsArr.push(num);
} else {
// Otherwise, set num to num squared and push that to the array.
num = Math.pow(num, 2);
resultsArr.push(num);
}
}
// Return the results array.
return resultsArr;
}
var powerOf = function (x, n) {
//create an array to store values
var array = [];
//loop through values and push them to the array
for (var i = 1; i < n; i++) {
array.push(x *= x);
}
//return array
return array;
};

Categories