how to add array values in javascript using push [closed] - javascript

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I have declared an array in JavaScript just view it.
var a[];
a.push(number);
alert(a);
I am trying to send an integer values using push but total numbers that I am sending are not fixed. I want to get sum of all numbers which are passing from this array.
If there is any other solution which can be usable in web.
a.push(number)
How can I add all values passing from this loop?

Please correct your JS code:
var
a = [],
sum = 0;
a.push(1);
a.push(2, 5);
for (var i in a) {
sum += a[i];
}
alert('Total sum is: ' + sum);
It will be better if you read complete reference about JavaScript's arrays from https://developer.mozilla.org

var total;
for (i = 0; i < a.length; i++) {
total += a[i] ;
}
alert(total);
a[i] will get the value of the given index which will be incremented with the previous value and the total sum will be stored in total variable

With an array, you can use the Reduce function to sum all elements:
var a = [1, 2, 3, 4, 5];
var sum = a.reduce(function(previousValue, currentValue, currentIndex, arr) {
return previousValue + currentValue;
});
document.write('The total is: ' + sum);

Related

How to use the reduce operation in javascript? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 1 year ago.
Improve this question
I am currently trying to simplify the following code written in Javascript
let x = 5;
let y = 10;
let z = 19;
let answer;
arrays = ["x", "y", "z"];
if("x" in arrays){
answer = x;
}
if("x" in arrays && "y" in arrays){
answer = x + y
}
The code will continue on and on for all the possible combinations of x, y and z. What I want to know is how I can simplify the above block of code and achieve the same result.
Thank you.
Instead of individual variables, create an object with your name/value pairs. Then it's trivial to iterate over the names in the array, use them to access the values in the object, and add them together. In fact, this is most naturally expressed as a reduce operation:
let vals = {
x: 5,
y: 10,
z: 19
};
let answer = ["x", "y", "z"].reduce((a, k) => a + vals[k], 0);
console.log(answer);

Array sum that I got from a for loop returns NaN (Javascript) [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
That function below returns NaN instead of expected 4. I bet there's some obvious mistake, but I'm not seeing it.
function myFunction(arr) {
let arrSum = 0
for (let i=0; i<=arr.length; i++) {arrSum += arr[i];}
return arrSum;
}
const myArr = [2,2];
console.log(myFunction(myArr));
you need to iterate till only i < arr.length arr[arr.length] will give undefined which will make your arrSum NaN.
function myFunction(arr) {
let arrSum = 0
for (let i=0; i<arr.length; i++) {arrSum += arr[i];}
return arrSum;
}
const myArr = [2,2];
console.log(myFunction(myArr));
Issue: Limiting condition of the for loop exceeds array size. Current array size is 2 and loop will iterate 3 times since i<=arr.length. So arr[2] will be undefined and it will lead to NaN.
Solution: For accessing elements in array, limiting condition should be i < arr.length.
Try the below code.enter code here
function myFunction(arr) {
let arrSum = 0
for (let i=0; i<arr.length; i++) {arrSum += arr[i];}
return arrSum;
}
const myArr = [2, 2];
console.log(myFunction(myArr));

replace number with string inside javascript array [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
Is it possible to replace a numeric value in a javascript array with a string?
for example:
var a=[1,2,3,4,5]
I need to replace #3 with apple.
Is it even possible?
Use .indexOf(3) to find where 3 is in the array, and then just do a[index] = "apple"; to replace the value. I created a snipped for you below.
var a = [1, 2, 3, 4, 5];
var index = a.indexOf(3);
console.log("Before: " + a);
a[index] = "apple";
console.log("After: " + a);
Aniket G's solution works, but only replaces the first occurrence of a value.
// arr is the array we're acting on
// n is the value we want to replace
// str is the string that we want n replaced with
function replaceNumWithStringInArray(arr, n, str) {
for (let i = 0; i < arr.length; ++i) {
if (arr[i] === n) {
// we found a match, replace the former value (n) with a string (str)
arr[i] = str;
}
}
// we don't have to return anything here, because it modifies the array in place
}
var a = [1,2,3,4,5,3]; // added another 3 to illustrate that it replaces all occurences of n
console.log('before', a);
replaceNumWithStringInArray(a, 3, 'apple');
console.log('after', a);
Yes, of course it's possible! I suggest you read some documentation on javascript arrays to see just how powerful they are.
Basically, javascript arrays are high-level list objects that can be made up of many different data-types. If you would have actually tried what you were curious about before asking about it here, you would have found it to be quite simple.
var a = [1,2,3,4,5];
a[2] = "apple";
Replaces the third element of array a with "apple".
You can iterate over your array and check for the given value. Especially useful if the value occurs multiple times:
function stringifyValue(array, valueToStringify) {
for(let i = 0; i < array.length; i++) {
if(array[i] === valueToStringify){
array[i] = '' + array[i];
}
}
}
Or if you want to update a value at the given index:
const indexWithValue = 3;
array[indexWithValue] = '' + array[indexWithValue];

Javascript Sherlock Array [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
Problem Statement
Watson gives Sherlock an array A of length N. Then he asks him to determine if there exists an element in the array such that the sum of the elements on its left is equal to the sum of the elements on its right. If there are no elements to the left/right, then the sum is considered to be zero. Formally, find an i, such that,
A1+A2...Ai−1=Ai+1+Ai+2...AN.
Input Format
The first line contains T, the number of test cases. For each test case, the first line contains N, the number of elements in the array A. The second line for each test case contains N space-separated integers, denoting the array A.
Output Format
For each test case print YES if there exists an element in the array, such that the sum of the elements on its left is equal to the sum of the elements on its right; otherwise print NO.
Constraints
1≤T≤10
1≤N≤105
1≤Ai≤2×104
1≤i≤N
Sample Input
2
3
1 2 3
4
1 2 3 3
Sample Output
NO
YES
Explanation
For the first test case, no such index exists. For the second test case,
A[1]+A[2]=A[4]
therefore index 3 satisfies the given conditions.
This solution features Array.prototype.some
The some() method tests whether some element in the array passes the test implemented by the provided function.
with a callback like
function isSherlock(_, i, a) {
function sum(i, n) {
return i < n ? a[i] + sum(i + 1, n) : 0;
}
return sum(0, i) === sum(i + 1, a.length);
}
where just the comparison is returned between the left side and the right side of the index, as well as it's recursive function
function sum(i, n) {
return i < n ? a[i] + sum(i + 1, n) : 0;
}
for counting the array values with the index smaller than the given value.
Alltogether as working example:
function isSherlock(_, i, a) {
function sum(i, n) {
return i < n ? a[i] + sum(i + 1, n) : 0;
}
return sum(0, i) === sum(i + 1, a.length);
}
document.write([1, 2, 3].some(isSherlock) + '<br>');
document.write([1, 2, 3, 3].some(isSherlock) + '<br>');

Sort array and return an array of indicies that indicates the position of the sorted elements with respect to the original elements (new) [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
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
Closed 9 years ago.
Improve this question
I have this array
test = [3, 2, 2, 1];
I want to be able to get this array
result = [3, 1, 2, 0]
The idea is the same as: Javascript: Sort array and return an array of indicies that indicates the position of the sorted elements with respect to the original elements
but incrementing the position value every time there is two elements on "test" with the same value.
You can pass a comparison function to sort:
var test = [3, 2, 2, 1];
var result = [];
for(var i = 0; i != test.length; ++i) result[i] = i;
result = result.sort(function(u,v) { return test[u] - test[v]; })
console.log(result) // [ 3, 1, 2, 0 ]

Categories

Resources