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) };
Related
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);
I'm pretty sure this is a basic question but my PHP background is making me unable to solve this. I was also unable to find a solution that came even close in SO.
I have an array of objects containing a value I want to loop and sum. Everything works well but I would like to directly sum those values to another array in the output.
So this is the working function:
function postsCalc(arrayEntry) {
var postsOutput = [];
var postLikes = 0;
for (var i = 0, len = arrayEntry.length; i < len; i++) {
postLikes += arrayEntry[i].likes.summary.total_count;
}
postsOutput.likes = postLikes;
return postsOutput;
}
Output:
likes : 55555;
Which works well, but can't I push it directly to the array key and avoid having to do the postsOutput.likes = postLikes?
Like this:
function postsCalc(arrayEntry) {
var postsOutput = [];
for (var i = 0, len = arrayEntry.length; i < len; i++) {
postsOutput.likes += arrayEntry[i].likes.summary.total_count;
// or even a multidimensional:
postsOutput.totals.likes += arrayEntry[i].likes.summary.total_count;
}
return postsOutput;
}
and that would output the same as above but avoiding the extra step, is this possible in Javascript?
Thanks in advance
You can use the reduce function on a list to do this:
function postsCalc(arrayEntry) {
var postLikes = arrayEntry.reduce(function(a, b) {return a + b.likes.summary.total_count}, 0);
return {likes: postLikes};
}
It works like this: Array.reduce(callback, initialValue) where callback = function(a, b) where a is the accumulator (e.g. tracks the sum, etc) and b is a representation of the item you're iterating over on the list. initialValue is the starting point for the function (e.g. on the first iteration).
Idiomatic javascript would look like (for your first function):
function postsCalc(arrayEntry) {
var postsOutput = {
postLikes: 0
};
for (var i = 0, len = arrayEntry.length; i < len; i++) {
postsOutput.postLikes += arrayEntry[i].likes.summary.total_count;
}
return postsOutput;
}
or, now that we can assume .forEach exists:
function postsCalc(arrayEntry) {
var postsOutput = {
postLikes: 0
};
arrayEntry.forEach(function(entry) {
postsOutput.postLikes += entry.likes.summary.total_count;
}
return postsOutput;
}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Array value count javascript
I have an array which contains several duplicates, what I'm trying to achieve is to count how many duplicates each unique string has in this one array.
The array looks something like this
array = ['aa','bb','cc','aa','ss','aa','bb'];
Thus I would like to do something like this
if (xWordOccurrences >= 5) {
// do something
}
But I'm not sure how I would code this.
I was thinking, create an object with each unique string, then loop through the original array, match each string with it's object and increment it's number by 1, then loop over the object to see which words had the most duplicates...
But this seems like an over complexe way to do it.
You can use an object which has keys of the Array's values and do something like this
// count everything
function getCounts(arr) {
var i = arr.length, // var to loop over
obj = {}; // obj to store results
while (i) obj[arr[--i]] = (obj[arr[i]] || 0) + 1; // count occurrences
return obj;
}
// get specific from everything
function getCount(word, arr) {
return getCounts(arr)[word] || 0;
}
getCount('aa', ['aa','bb','cc','aa','ss','aa','bb']);
// 3
If you only ever want to get one, then it'd be more a bit more efficient to use a modified version of getCounts which looks similar to getCount, I'll call it getCount2
function getCount2(word, arr) {
var i = arr.length, // var to loop over
j = 0; // number of hits
while (i) if (arr[--i] === word) ++j; // count occurance
return j;
}
getCount2('aa', ['aa','bb','cc','aa','ss','aa','bb']);
// 3
Try this function:
var countOccurrences = function(arr,value){
var len = arr.length;
var occur = 0;
for(var i=0;i<len;i++){
if(arr[i]===value){
occur++;
}
}
return occur;
}
var count = countOccurrences(['aaa','bbb','ccc','bbb','ddd'],'bbb'); //2
If you want, you can also add this function to the Array prototype:
Array.prototype.countOccurrences = function(value){
var len = this.length;
var occur = 0;
for(var i=0;i<len;i++){
if(this[i]===value){
occur++;
}
}
return occur;
}
How about you build an object with named property?
var array = ['aa','bb','cc','aa','ss','aa','bb'];
var summary = {};
var item = '';
for ( i in array){
item = array[i];
if(summary[item]){
summary[item] += 1;
}
else{
summary[item] = 1;
}
}
console.log( summary );
summary will contain like this
{aa: 3, bb: 2, cc: 1, ss: 1}
which you could then iterate on and then sort them later on if needed.
finally to get your count, you could use this summary['aa']
<script type="text/javascript">
var array = ['aa','bb','cc','aa','ss','aa','bb'];
var myMap = {};
for(i = 0; i < array.length; i++) {
var count = myMap[array[i]];
if(count != null) {
count++;
} else {
count = 1;
}
myMap[array[i]] = count;
}
// at this point in the script, the map now contains each unique array item and a count of its entries
</script>
Hope this solves your problem
var array = ['aa','bb','cc','aa','ss','aa','bb'];
var dups = {};
for (var i = 0, l = array.length; i < l; i++ ) {
dups[array[i]] = [];
}
for (str in dups) {
for (var i = 0, l = array.length; i < l; i++ ) {
if (str === array[i]) {
dups[str].push(str);
}
}
}
for (str in dups) {
console.log(str + ' has ' + (dups[str].length - 1) + ' duplicate(s)');
}
This function may do everything you need.
function countDupStr(arr, specifier) {
var count = {}, total = 0;
arr.forEach(function (v) {
count[v] = (count[v] || 0) + 1;
});
if(typeof specifier !== 'undefined') {
return count[specifier] - 1;
}
Object.keys(count).forEach(function (k) {
total += count[k] - 1;
});
return total;
}
Each value in the array is assigned and incremented to the count object. Whether or not a specifier was passed, the function will return duplicates of that specific string or the total number of duplicates. Note that this particular technique will only work on string-coercible values inside your arrays, as Javascript can only index objects by string.
What this means is that during object assignment, the keys will normalize down to strings and cannot be relied upon for uniqueness. That is to say, this function wouldn't be able to discern the difference between duplicates of 3 and '3'. To give an example, if I were to perform:
var o = {}, t = {};
o[t] = 1;
console.log(o);
The key used in place of t would eventually be t.toString(), thus resulting in the perhaps surprising object of {'[object Object]': 1}. Just something to keep in mind when working with Javascript properties.
I saw this post about it, perhaps it can help:
http://ryanbosinger.com/blog/2011/javascript-count-duplicates-in-an-array/
Which is the best way to set an array of n dimensions from a function?
var v1 = [1,2,3];
var v2 = [[1,2],[3,4]];
// only valid for 1-dimension
function set(arr, dim, v) {
arr[dim] = v;
}
set(v1, 2, 33);
Your function can't work as designed it needs an index for each dimension
You'd need something like the following http://jsfiddle.net/nZmJT/1/
function setValueInArray(arr, value, index /*, index, index, ... */ ) {
var arrToSet = arr;
for (var i = 2; i < arguments.length - 1; i++) {
arrToSet = arr[arguments[i]];
}
arrToSet[arguments[i]]= value;
return arr;
}
var v1 = [1,2,3];
var v2 = [[1,2],[3,4]];
console.log( setValueInArray(v1, 0, 0) ); // [0,2,3]
console.log( setValueInArray(v2, 0, 0, 0) ); //[[0,2],[3,4]]
Please share with us why you'd like this. I can't think of code that can be generalized to work with multiple dimensions, you usually know the dimension, and just set it like...
v1[2][3] = 'anything';
Since in your case, you wouldn't know how many indexes to pass (otherwise you'd just use bracket access), the following may be a better fit
function setValueInArray(arr, value, indexes) {
var arrToSet = arr;
for (var i = 0; i < indexes.length - 1; i++) {
arrToSet = arr[indexes[i]];
}
arrToSet[indexes[i]] = value;
return arr;
}
Then you can call it passing the array of indexes which is created by some code outside of your control.
setValueInArray(v1, 0, indexes);
I have a array like
arr[1] = 234;
arr[2] = 345;
...
arr[40] = 126;
How can I get the index of the element with the highest value without reiterating the array?
You can apply Math.max and pass the array as its arguments-
arr.indexOf(Math.max.apply(window,arr))
But now Math.max is doing the iterating, just as sort would do.
Somebody has to look at each item in an unsorted array...
With jQuery, is as simple as:
// Get the max value from the array
maxValue = Math.max.apply(this, arr);
// Get the index of the max value, through the built in function inArray
$.inArray(maxValue,arr);
If the array is not ordered you cannot do this without iterating.
Get the array key with the highest value in javascript
var cars = ["Saab", "Volvo", "BMW"];
var max_car_result = cars[cars.length-1];
alert(max_car_result);
Try this:
var max_index = -1;
var max_value = Number.MIN_VALUE;
for(var i = 0; i < arr.length; i++)
{
if(arr[i] > max_value)
{
max_value = arr[i];
max_index = i;
}
}
You could use a function to set the variable. And keep track of the max in that function. Here's a quick example without type checking, testing, or support for removing a value.
Array.prototype.maxValue = null;
Array.prototype.setIndex = function(index, value){
this[index] = value;
if (value > this.maxValue || this.maxValue == null)
this.maxValue = value;
}
var arr = new Array();
arr.setIndex(0, 234);
arr.setIndex(1, 500);
arr.setIndex(2, -5);
var maxValue = arr.maxValue;
Obviously this is nicer if you're currently setting items like this:
var arr = new Array();
arr[0] = 1;
arr[1] = 500;
arr[2] = 2;
Rather than this:
var arr = { 1, 500, 2 };
The downside is its not natural and requires you to use function to get the correct results.
Keep the array sorted or use a heap.
Otherwise iterate. Even if you found some trick to do it it would still require iterating underneath so why not iterate?
If it seems like too much code, put it in a separate routine.
Two solution: to sort descending order and get the first element or:
function bigger(array) {
if (array.length < 1) {
return -1;
}
bigger = 0;
for(var i=1; i<array.length;i++ ) {
if(array[i] > array[bigger]) {
bigger = i;
}
}
return bigger;
}
you cold optimize using two variables, one for the position and other for the content.
Either you will have iteration somewhere (in your code or in JQuery.each()) or you can define something like this:
Array.prototype.mpush = function(v)
{
var maxv = this.maxValue || Number.MIN_VALUE;
if( v > maxv ) { this.maxValue = v; this.maxIndex = this.length; }
this.push(v);
}
and use that arr.mpush(v) to populate your array. In this case the array will have maxIndex property.
Is old question but here is an my simple emulation of PHP script max() made in javascript:
function max(array){
if(Object.prototype.toString.call( array ) === '[object Array]'){
return array[(array.length-1)];
}
else return 0;
}
This return value of last key in array or 0 if nothing found.
Maby someone helps.
You can use it like:
var array = ['bananaman','spiderman','ironman','superman','batman','manman'];
var getLast = max(array);
if(getLast !== 0)
alert(getLast); // manman