confusion regarding array.average() functionality in "var avg = array.average()" - javascript

Cheers guys. I was asked to make this code work in a learning challenge and I'm not sure how to tackle the "array.average()" part, as it's not a function.
What I was asked was this:
var array = [5,44,23,11,55,68];
var avg = array.average();
console.log(avg);
So far, I've tackled the averaging of the array like this:
function average(){
var total = 0;
for (var i = 0; i < array.length; i++) {
total += array[i];
}
var avg = total / array.length;
}
Any and all corrections are welcome. This is 100% learning based so everything helps.

First attach the function to your array object, and then make sure to return a value at the end of it:
var array = [5,44,23,11,55,68];
array.average = () => {
var total = 0;
for (var i = 0; i < array.length; i++) {
total += array[i];
}
var avg = total / array.length;
return avg;
}
var avg = array.average();
console.log(avg);
(avoid mutating native prototypes)

Suppose you need to add it in the Array.prototype (which is a bad idea), use Object.defineProperty to add it in as non-enumerable and won't clash with other native methods:
var array = [5,44,23,11,55,68];
Object.defineProperty(Array.prototype, 'average', {
enumerable: false,
value: () => array.reduce((a,b) => a + b) / array.length
});
console.log(array.average())

Add average function to Array.prototype:
var arr = [5,44,23,11,55,68];
Array.prototype.average = function() {
return this.reduce(function(acc, cur) { return (acc + cur); }, 0) / this.length;
}
var avg = arr.average();
console.log(avg);

Related

How to iterate to 100 using a for or while loop and show the sum of each iteration with javascript?

Just doing a small homework. I need to iterate to 100, but also console.log the result of each previous example.
Example of the series: (1)+(1+2)+(1+2+3)+…+(1+2+3+…+n)<=100
Iteracion1=1
Iteracion2= 1+2 = 3
iteracion 3: 1+2+3 = 6
iteracion 4: 1+2+3+4 = 10
I have this:
for (i = 0; i <= 100; i++) {
if(i < 100) {
console.log(`${i}+${1}`);
}};
But I don't know how to add the sum of it on each iteration. I you have any references for this it would be great! thank you.
You can efficiently achieve the result using a single loop.
For demo purposes, I've printed up to 20. You can add any number of your choice.
let lastTotal = 0;
let lastStr = "";
for (let i = 1; i <= 10; ++i) {
const total = (lastTotal ?? 0) + i;
const str = lastStr ? lastStr + " + " + i : i;
console.log(`Iteration ${i}: ${str}${total === 1 ? "" : " = " + total}`);
lastTotal = total;
lastStr = str;
}
/* This is not a part of answer. It is just to give the output fill height. So IGNORE IT */
.as-console-wrapper { max-height: 100% !important; top: 0; }
You can use variables outside of for to achieve this
let sum = 0;
const previousSums = [];
for (i = 0; i < 100; i++) {
previousSums.push(sum);
sum += i;
console.log(`${previousSums}`);
}
Create an array you can add indexes to.
Create a function that calculates the sum of the numbers in the array. I've used reduce here.
Create a string, and then log it.
const arr = [];
function sum(arr) {
return arr.reduce((acc, c) => acc + c, 0);
}
// On each iteration push the index in to the
// array. Create a string that joins up the array
// elements and logs the result of the sum
for (let i = 1; i <= 10; i++) {
arr.push(i);
const str = `Iteration ${i}: ${arr.join('+')} = ${sum(arr)}`;
console.log(str);
};
This should do fine.
I created a new Array for the length of iteration of i and use Array#reduce to sum it all up to a number.
const max = 10;
for (let i = 1; i <= max; i++) {
const arr = new Array(i).fill().map((_, i) => i + 1);
console.log(`Iteration ${i}: ${arr.join('+')} = ${arr.reduce((acc, b) => acc + b, 0)}`);
}
var total = 0;
var res = 0;
var upto = 6;
for(i=1;i<=upto;i++){
total = total+i;
res = res+total;
}
console.log(res);

Make an array filled with numbers 1 to 10000 and then sum all of those numbers [duplicate]

This question already has answers here:
How to find the sum of an array of numbers
(59 answers)
Closed 6 years ago.
How can I turn this into a function that takes an array of any length and gives you the total?
var points = new Array(100);
for (var i = 0; i < 100; i++) {
points[i] = i + 1;
}
for(var i = 0; i < points.length; i++) {
console.log(points[i]);
}
You could do it in two loops, but you might as well just do one loop that does both tasks.
var array = [],
sum = 0;
for (var i = 1; i <= 10000; i++) {
array[i-1] = i;
sum += i;
}
If you want to generalize the task of finding the sum of an array, you can use a function like so:
function arraySum(array) {
var sum = 0;
for (var i = 0; i < array.length; i++)
sum += array[i];
return sum;
}
For those who can understand it though, using reduce is a best answer:
function arraySum(array) {
return array.reduce(function(a,b){return a+b}, 0);
}
You can do get the sum using the for loop itself simply by using a variable
var points = new Array(100),
sum = 0;
for (var i = 0; i < 100; i++) {
points[i] = i + 1;
}
for (var i = 0; i < points.length; i++) {
sum += points[i];
}
console.log(sum);
You can reduce these two operations using fill() and forEach() to generate the array and reduce() to get the sum
var points = new Array(10000); // create an array of size 10000
points.fill(1); // fill it with 1 which helps ti=o iterate using foreach
points.forEach(function(v, i) { // iterate the array, you can also use simple for loop here
points[i] = v + i; // update the value
});
var sum = points.reduce(function(a, b) { // find sum
return a + b;
});
console.log(sum);
Using for loop and reduce()
var points = []; // initialize an array
for (var i = 1; i <= 10000; i++) {
points.push(i);
}
var sum = points.reduce(function(a, b) { // find sum
return a + b;
});
console.log(sum);
Also you can do the addition and array creation in single for loop
var points = [], // initialize an array
sum = 0;
for (var i = 1; i <= 10000; i++) {
points.push(i); // pushing value to array
sum += i; // summation
}
console.log(sum, points);
var result = 0;
for(var i = 0; i < points.length; i++) {
result += points[i];
}
Function that takes an array of any length and returns the sum:
function sumArray(arrayToSum){
var result = 0;
for(var i = 0; i < arrayToSum.length; i++) {
result += points[i];
}
return result;
}
function arraysum(arraylength) {
var arraysum = 0;
var array1 = new Array();
for(i=1; i<=arraylength; i++) {
array1.push(i);
}
for(i = 0; i< array1.length; i++) {
arraysum += array1[i];
}
return arraysum;
}
Now when you call the function
arraysum(x)
pass the function some variable or integer for example 1, 15, or 10000.
A very elegant and compact solution is to use reduce. It accumulates the array values to reduce it to a single value by applying each value and a start value to a given function, whose return value is used as the start value for the next iteration:
function sum (a, b) {
return a + b;
}
console.log(points.reduce(sum, 0));
If you need to support older browser (e.g. IE 8) you can use a Polyfill.
If you need to create the list of numbers as well, you can create it with
var points = Array.apply(0, Array(10000))
.map(function (current, index) {
return index + 1;
});
It creates an array of 10000 elements and assigns each element it's index + 1.

How to chop a large array into smaller chunks of fixed length

I've a Float32Array of 10659503 elements in length. I want to chunk (split) it into small arrays of fixed length. How to do that? I've tried the method bellow it's not working:
var LENGTH = 4096;
var chunking = function(data) {
var chunks = [];
for (var i = 0; i < data.length; i += LENGTH) {
var index = ~~(i/LENGTH);
var offset = i%LENGTH;
if (offset === 0) {
chunks[i] = data.subarray(i, LENGTH);
}
}
console.log(chunks);
}
Thank you,
You can use Float32Array.subarray() get the sliced view of the original array.
function chunking(data, length) {
var result = [];
for (var i = 0; i < data.length; i += length) {
result.push(data.subarray(i, i + length));
}
return result;
}
console.log(chunking(new Float32Array(100), 12));
In general case I would do it using splice
function chunk(data, LENGTH) {
var ret = []
while (data.length) {
ret.push(data.splice(0,LENGTH))
}
return ret
}
But since Float32Array doesn't have this method in prototype (thanks #Felix Kling), it is going to be little bit more complicated:
function chunk(data, LENGTH) {
var ret = []
while (data.length) {
ret.push([].splice.call(data, 0, LENGTH))
}
return ret
}
However, since you probably want to avoid coping data back and forth in memory, you have to use methods that just create new ArrayBufferView without moving actual data. And that is exactly what subarray method is doing. So #thefourtheye answer is the right way to go.
Try this:
newArray = (function(array, chunk) {
retArr = [];
for (var i = 0; i < array.length; i+=chunk)
retArr.push(array.slice(i,i+chunk));
return retArr;
}(oldArray, chunkSize))
http://jsfiddle.net/R3Ume/7/

Take an input single dimensional array [1,2,3,4] and output the product of the integers excluding the current index [24,12,8,6];

Guys I need your opinion; I've encountered this earlier during my interview, I just want to confirm I understood the question right and I got the answer correctly. Thank you. Please check the question and my answer below:
Take an input single dimensional array [1,2,3,4] and output the product of the integers excluding the current index [24,12,8,6];
//My answer
function calculate(values:Array):Array {
var resultArray:Array = new Array();
for(var i:int = 0; i < values.length; i++) {
var getVal1:Number = 1;
for(var k:int = 0; k <= values.length; k++) {
if(i != k) {
var getVal2:Number = values[k];
getVal1 *= getVal2;
}
}
resultArray.push(getVal1);
}
return resultArray;
}
Nested loops seems like a very messy way to go.
Assuming relatively up-to-date browser (IE 8 and below are out) or suitable shim:
var resultArray = sourceArray.map(function(val,ind,arr) {
arr = arr.slice(0); // create copy of array to work on here
arr.splice(ind,1); // remove current item from array
return arr.reduce(function(prev,curr) {return prev*curr;},1);
});
Array.prototype.map
Array.prototype.reduce
EDIT Here's another way that should be more efficient:
var product = sourceArray.reduce(function(prev,curr) {return prev*curr;},1);
var resultArray = sourceArray.map(function(val) {return product/val;});
Your solution gives the correct answer, but there is a much more efficient method to calculate the new array:
function calculate(values:Array):Array {
var resultArray:Array = new Array();
var product:int = 1;
for(var i:int = 0; i < values.length; i++) {
product *= values[i];
}
for(var i:int = 0; i < values.length; i++) {
resultArray.push(product / values[i]);
}
return resultArray;
}
This solution has O(n) execution time, while your code has O(n²) execution time.
That should work. You can do it easier and more efficiently by multiplying all items first:
function calculate(values) {
var prod = 1;
for (var i = 0; i < values.length; i++) prod *= values[i];
var result = [];
for (i = 0; i < values.length; i++) result.push(prod / values[i]);
return result;
}
I believe that my code below is very easy to read. And has no nested loops, but two consecutives. My answer would be:
function calculate(array){
var total = array.reduce(function(a, b){
return a * b;
});
return array.map(function(element){
return total / element;
});
}
Though I like #Kolink's short-and-efficient solution best, here's another way to solve the task - not using division but still being in O(n):
function calculate(values) {
var acc = 1,
l = values.length,
result = new Array(l);
for (var i=0; i<l; i++) {
result[i] = acc;
acc *= values[i];
}
acc = 1;
while(i--) {
result[i] *= acc;
acc *= values[i]
}
return result;
}
Or, the same thing but a little obfuscated*:
function calculate(values) {
var acc = 1,
i = 0,
l = values.length,
result = new Array(l);
if (l)
result[i] = 1;
while( ++i < l)
result[i] = acc *= values[i-1];
i -= acc = 1;
while (i--)
result[i] *= acc *= values[i+1];
return result;
}
*: I like shorthand operators!

Abstract function to sum elements of an Array

I have like 40 different arrays and I want to find the average value of each of them.
In order to do it with each one, I have this code:
var SumArray1 = 0;
var avgArray1 = 0;
$.each(array1,function() {
SumArray1 += this;
avgArray1 = (SumArray1)/(array1.length);
});
But as I have those 40 arrays, I was trying to look for a way to make that function abstract, but I don't know how to introduce parameters for a function using $.each and I don't think having forty functions would be the right thing to do...
Thanks!
Your implementation calculates the average each time, but it only gets a correct value the last time. This is not necesary.
Also, there's no need to use $.each, which forces you to use an additional closure (my previous statement about waiting was wrong, since $.each is synchronous).
The following is simpler:
function avgArray(array) {
var i,l,s = 0;
for (i=0,l=array.length; i<l; i++) s+= array[i];
return s/l;
}
Add this code:
Array.prototype.average = function() {
var s = 0;
for(var i = 0; i < this.length; ++i) {
s += this[i];
}
return s/this.length;
}
Then at any point you can do something like
var myArray = [1,2,3,4];
var calculatedAverage = myArray.average(); // This will equal 2.5
Arrays have a built in reduce function, if you like short one-liners you can also do this:
var arr = [1,2,3,4];
function sum(x,y){
return x + y;
}
var total = arr.reduce(sum); // total -> 10
// This also works
var total = arr.reduce( function(x,y) { return (x + y); } );
var avg = ( total / arr.length );
Reduce is a higher-order function that 'reduces' an sequence into a single value.
Here is the execution flow of reduce.
var temp = sum( arr[0], arr[1] );
temp = sum( temp, arr[2] );
temp = sum( temp, arr[3] );
return temp;
Stealing Andrew Shepherd answer for adding new functions to the Array data structure.
Array.prototype.sum = function() { return this.reduce( function(x,y) { return (x+y); } )};
Array.prototype.avg = function() { return (this.sum() / this.length) };

Categories