This question already has answers here:
Finding the average of an array using JS [duplicate]
(9 answers)
Closed 7 years ago.
I Want To Calculate Average Value Of Array Elements Using Java Script. I am an beginner in Java Script, So Please Give me the easiest & understandable code
Assuming that all items in your array are numbers, loop through them, and sum them. Once you have a sum of all items, divide this figure by number of items (your_array.length) and then you'll get your average.
Show your existing code, what you have done so far?
Not tested, pseudo code:
var array = [1, 6, 43, 2, 8];
var sum = 0;
for (var i = 0; i < array.length; i++) {
sum += parseInt(array[i]);
}
if (array.length > 0) {
console.log('Average is ' + (sum / array.length));
}
Related
This question already has answers here:
Efficient way to insert a number into a sorted array of numbers?
(18 answers)
Closed 2 years ago.
What is the best way to insert value in an array and keep the array sorted?
for example here is an array
const arr = [1, 4, 23, 45];
I can add a new value using method push or splice, for example 16, and I'll get modified array:
[1, 4, 23, 45, 16]
But I need to keep array sorted:
[1, 4, 16, 23, 45]
What is the better way to keep array sorted? Should I sort every time when add a new value, or detect necessary index for inserting a new value?
Just look at the complexities:
SORTING: O(nlogn) in the best scenario
INDEX INSERT: O(n) in the worst scenario
SORTING SMART: O(n) in the best scenario, using algorithms like insertionSort, that work very well when the array is almost already sorted
BINARY INSERTION: O(logn) this is the preferred way
function binaryInsertion(arr, element) {
return binaryHelper(arr, element, 0, arr.length - 1);
}
function binaryHelper(arr, element, lBound, uBound) {
if (uBound - lBound === 1) {
// binary search ends, we need to insert the element around here
if (element < arr[lBound]) arr.splice(lBound, 0, element);
else if (element > arr[uBound]) arr.splice(uBound+1, 0, element);
else arr.splice(uBound, 0, element);
} else {
// we look for the middle point
const midPoint = Math.floor((uBound - lBound) / 2) + lBound;
// depending on the value in the middle, we repeat the operation only on one slice of the array, halving it each time
element < arr[midPoint]
? binaryHelper(arr, element, lBound, midPoint)
: binaryHelper(arr, element, midPoint, uBound);
}
}
console.log("even array test");
var array = [1,3,4,5,9];
binaryInsertion(array, 2);
console.log(array);
console.log("odd array test");
var array = [1,3,5,7,9,11,13,15];
binaryInsertion(array, 10);
console.log(array);
console.log("beginning and end test");
var array = [2,3,4,5,9];
binaryInsertion(array, 0);
binaryInsertion(array, 10);
console.log(array);
Im just wondering who can explain the algorithm of this solution step by step. I dont know how hashmap works. Can you also give a basic examples using a hashmap for me to understand this algorithm. Thank you!
var twoSum = function(nums, target) {
let hash = {};
for(let i = 0; i < nums.length; i++) {
const n = nums[i];
if(hash[target - n] !== undefined) {
return [hash[target - n], i];
}
hash[n] = i;
}
return [];
}
Your code takes an array of numbers and a target number/sum. It then returns the indexes in the array for two numbers which add up to the target number/sum.
Consider an array of numbers such as [1, 2, 3] and a target of 5. Your task is to find the two numbers in this array which add to 5. One way you can approach this problem is by looping over each number in your array and asking yourself "Is there a number (which I have already seen in my array) which I can add to the current number to get my target sum?".
Well, if we loop over the example array of [1, 2, 3] we first start at index 0 with the number 1. Currently, there are no numbers which we have already seen that we can add with 1 to get our target of 5 as we haven't looped over any numbers yet.
So, so far, we have met the number 1, which was at index 0. This is stored in the hashmap (ie object) as {'1': 0}. Where the key is the number and the value (0) is the index it was seen at. The purpose of the object is to store the numbers we have seen and the indexes they appear at.
Next, the loop continues to index 1, with the current number being 2. We can now ask ourselves the question: Is there a number which I have already seen in my array that I can add to my current number of 2 to get the target sum of 5. The amount needed to add to the current number to get to the target can be obtained by doing target-currentNumber. In this case, we are currently on 2, so we need to add 3 to get to our target sum of 5. Using the hashmap/object, we can check if we have already seen the number 3. To do this, we can try and access the object 3 key by doing obj[target-currentNumber]. Currently, our object only has the key of '1', so when we try and access the 3 key you'll get undefined. This means we haven't seen the number 3 yet, so, as of now, there isn't anything we can add to 2 to get our target sum.
So now our object/hashmap looks like {'1': 0, '2': 1}, as we have seen the number 1 which was at index 0, and we have seen the number 2 which was at index 1.
Finally, we reach the last number in your array which is at index 2. Index 2 of the array holds the number 3. Now again, we ask ourselves the question: Is there a number we have already seen which we can add to 3 (our current number) to get the target sum?. The number we need to add to 3 to get our target number of 5 is 2 (obtained by doing target-currentNumber). We can now check our object to see if we have already seen a number 2 in the array. To do so we can use obj[target-currentNumber] to get the value stored at the key 2, which stores the index of 1. This means that the number 2 does exist in the array, and so we can add it to 3 to reach our target. Since the value was in the object, we can now return our findings. That being the index of where the seen number occurred, and the index of the current number.
In general, the object is used to keep track of all the previously seen numbers in your array and keep a value of the index at which the number was seen at.
Here is an example of running your code. It returns [1, 2], as the numbers at indexes 1 and 2 can be added together to give the target sum of 5:
const twoSum = function(nums, target) {
const hash = {}; // Stores seen numbers: {seenNumber: indexItOccurred}
for (let i = 0; i < nums.length; i++) { // loop through all numbers
const n = nums[i]; // grab the current number `n`.
if (hash[target - n] !== undefined) { // check if the number we need to add to `n` to reach our target has been seen:
return [hash[target - n], i]; // grab the index of the seen number, and the index of the current number
}
hash[n] = i; // update our hash to include the. number we just saw along with its index.
}
return []; // If no numbers add up to equal the `target`, we can return an empty array
}
console.log(twoSum([1, 2, 3], 5)); // [1, 2]
A solution like this might seem over-engineered. You might be wondering why you can't just look at one number in the array, and then look at all the other numbers and see if you come across a number that adds up to equal the target. A solution like that would work perfectly fine, however, it's not very efficient. If you had N numbers in your array, in the worst case (where no two numbers add up to equal your target) you would need to loop through all of these N numbers - that means you would do N iterations. However, for each iteration where you look at a singular number, you would then need to look at each other number using a inner loop. This would mean that for each iteration of your outer loop you would do N iterations of your inner loop. This would result in you doing N*N or N2 work (O(N2) work). Unlike this approach, the solution described in the first half of this answer only needs to do N iterations over the entire array. Using the object, we can find whether or not a number is in the object in constant (O(1)) time, which means that the total work for the above algorithm is only O(N).
For further information about how objects work, you can read about bracket notation and other property accessor methods here.
You may want to check out this method, it worked so well for me and I have written a lot of comments on it to help even a beginner understand better.
let nums = [2, 7, 11, 15];
let target = 9;
function twoSums(arr, t){
let num1;
//create the variable for the first number
let num2;
//create the variable for the second number
let index1;
//create the variable for the index of the first number
let index2;
//create the variable for the index of the second number
for(let i = 0; i < arr.length; i++){
//make a for loop to loop through the array elements
num1 = arr[i];
//assign the array iteration, i, value to the num1 variable
//eg: num1 = arr[0] which is 2
num2 = t - num1;
//get the difference between the target and the number in num1.
//eg: t(9) - num1(2) = 7;
if(arr.includes(num2)){
//check to see if the num2 number, 7, is contained in the array;
index1 = arr.indexOf(num2);
//if yes get the index of the num2 value, 7, from the array,
// eg: the index of 7 in the array is 1;
index2 = arr.indexOf(num1)
//get the index of the num1 value, which is 2, theindex of 2 in the array is 0;
}
}
return(`[${index1}, ${index2}]`);
//return the indexes in block parenthesis. You may choose to create an array and push the values into it, but consider space complexities.
}
console.log(twoSums(nums, target));
//call the function. Remeber we already declared the values at the top already.
//In my opinion, this method is best, it considers both time complexity and space complexityat its lowest value.
//Time complexity: 0(n)
function twoSum(numbers, target) {
for (let i = 0; i < numbers.length; i++) {
for (let j = i + 1; j < numbers.length; j++) {
if (numbers[i] + numbers[j] === target) {
return [numbers.indexOf(numbers[i]), numbers.lastIndexOf(numbers[j])];
}
}
}
}
This question already has answers here:
Sum of a javascript array returns a string concatenation of all the numbers [closed]
(3 answers)
Closed 3 years ago.
I'm trying to reduce an array of numbers into the sum of all the numbers combined. At the moment I'm using Array.reduce to try and achieve this, but what I'm finding is that this function only stacks the array's values to create one massive number rather than summing them all together.
// Function used to get the sum of all numbers in array
function getSum(total, num){
return total + num;
// Reduce Var
var easternSum = scoreEastern.reduce(getSum);
// Dynamic array based on user input
var scoreEastern = dataSet
.filter(scoreEastern => scoreEastern.Course === 'eastern')
.map(({Score}) => Score);
// Empty array that scoreEastern var is assigned to
var dataSet = [];
Because my array is dynamic, it's based on what the user inputs into a form, there's no set array. But let's say the array is:
var scoreEastern = [10, 20, 30]
The reduce var easternSum will result in the number 102,030. What I want is 60.
I think maybe scoreEastern doesn't have the data that you expect all the time? You mentioned that it is dynamic. This snippet appears to work for the use case you posted in your question.
const scoreEastern = [10, 20, 30];
console.log(scoreEastern.reduce((prev, curr) => prev + curr));
This question already has answers here:
How to get first N number of elements from an array
(14 answers)
Closed 5 years ago.
i would like to get the first 3 elements of an array of variable length. i've sorted my array and i would like to get a Top 3.
here's what i've done :
var diffSplice = this.users.length - 1;
return this.users.sort(this.triDec).splice(0,diffSplice)
my "solution" work only for an array of 4 element ( -1 )
Is there a better way to use the splice method ?
Thanks for your help
You could use Array#slice for the first three items.
return this.users.sort(this.triDec).slice(0, 3);
Don't you want to use a const value for diffSplice like
var diffSplice = 3;
return this.users.sort(this.triDec).slice(0,diffSplice)
try running
let arr = [1, 2, 3, 4, 5];
console.log(arr.slice(0, 3));
refer to Array Silce
Fill out the deletecount for Splice:
var sortedArray = this.users.sort(this.triDec);
return sortedArray.splice(0, 3);
check MDN
This question already has answers here:
Why does javascript turn array indexes into strings when iterating?
(6 answers)
Is a JavaScript array index a string or an integer?
(5 answers)
Why is key a string in for ... in
(3 answers)
When iterating over values, why does typeof(value) return "string" when value is a number? JavaScript
(1 answer)
Closed 1 year ago.
I've simplified my program down to this, and it's still misbehaving:
var grid = [0, 1, 2, 3];
function moveUp(moveDir) {
for (var row in grid) {
console.log('row:');
console.log(row + 5);
}
}
It seems that row is a string instead of an integer, for example the output is
row:
05
row:
15
row:
25
row:
35
rather than 5, 6, 7, 8, which is what I want. Shouldn't the counter in the for loop be a string?
Quoting from MDN Docs of for..in,
for..in should not be used to iterate over an Array where index order
is important. Array indexes are just enumerable properties with
integer names and are otherwise identical to general Object
properties. There is no guarantee that for...in will return the
indexes in any particular order and it will return all enumerable
properties, including those with non–integer names and those that are
inherited.
Because the order of iteration is implementation dependent, iterating
over an array may not visit elements in a consistent order. Therefore
it is better to use a for loop with a numeric index (or Array.forEach
or the non-standard for...of loop) when iterating over arrays where
the order of access is important.
You are iterating an array with for..in. That is bad. When you iterate with for..in, what you get is the array indices in string format.
So on every iteration, '0' + 5 == '05', '1' + 5 == '15'... is getting printed
What you should be doing is,
for (var len = grid.length, i = 0; i < len; i += 1) {
console.log('row:');
console.log(grid[i] + 5);
}
For more information about why exactly array indices are returned in the iteration and other interesting stuff, please check this answer of mine
You should use a normal for loop rather than a for...in loop for arrays.
for (var row = 0, l = grid.length; row < l; row++) {
console.log('row:');
console.log(5 + row);
}
I think this is what your expected output should be.
Fiddle
Try with parseInt(..) method to force int value
console.log(parseInt(row,10) + 5);
second param 10 is to be parsed as decimal value.
See the answer here How do I add an integer value with javascript (jquery) to a value that's returning a string?