This question already has answers here:
How to find the sum of an array of numbers
(59 answers)
Closed 3 months ago.
We have an array with the name; chess_players, in each element of the array there is an object with two properties: the name of a chess player and the points he has obtained. In this activity, a function must be created (which allows code reuse, that is, if the table is extended with more players, the function must continue to work without having to modify anything). The created function must receive the object as a parameter and return the name of the chess player who has obtained the most points.
This is what I tried:
let chess_players = [{name:"Jackson",points:[900,1000,3000,1950,5000]},{name:"Steve",points:[300,400,900,1000,2020]}]
function returnName(object){
/* With this for in loop, I'm trying to iterate through each array to calculate the sum of each array */
for (var num in object){
var index = 0;
var length = object.length;
var sum = 0;
/* I try to return the maximum value */
sum += object.fact[index ++]
var maxVal = Math.max(...sum);
}
return array[index].name;
}
console.log(returnName(chess_players))
I would perhaps use reduce method and calculate the total points of each player. then sort them descending order. and finally retrieve the name of player.
let chess_players = [{name:"Jackson",points:[900,1000,3000,1950,5000]},
{name:"Steve",points:[300,400,900,1000,2020]}]
const returnName = theObject =>
theObject.map(({name, points})=>({name, totalPoints:points.reduce((acc , current) => acc + current)})).sort((a,b)=> b.totalPoints - a.totalPoints)[0].name
console.log(returnName(chess_players))
Step by step:
const chess_players = [{name:"Jackson",points:[900,1000,3000,1950,5000]},{name:"Steve",points:[300,400,900,1000,2020]}]
function returnName(theObject){
const arrOfTotalVal = theObject.map(obj => obj.points.reduce((a, c) => a + c));
const maxVal = Math.max(...arrOfTotalVal);
const index = arrOfTotalVal.indexOf(maxVal);
return theObject[index].name;
}
console.log(returnName(chess_players));
Related
This question already has answers here:
What does the range method getValues() return and setValues() accept?
(1 answer)
Remove empty elements from an array in Javascript
(49 answers)
Closed 2 years ago.
I have a for loop. The purpose of the loop is to index a one dimensional array of 5 numbers within a two dimensional array, then add the numbers in that array together and place it in on another sheet (testSheet). It's returning text like "0,45,,,40". The program works fine, other than it's not adding the numbers together. I'm guessing this is because some of the cells are null and it's not recognizing them as numbers.
for (var i=0; i < arrTarget.length; i++){
//find Row
var row = arrSource.indexOf(arrTarget[i]);
var numArr = shrinkLog.getRange(row+3,4,5).getValues();
//add units in an array
var sum = numArr.reduce(function(a,b){return a+b;},0);
//execute
var testsheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("test Sheet");
testsheet.getRange(i+1,1,1,1).setValue(sum);
}
Can someone help how I get the program to recognize the null cells as the number 0?
Explanation:
The main issue is that numArr is a two dimensional array in the form of [[],[],[]]. To see why is that, please go through this very useful post.
There are two steps you need to follow to accomplish your goal:
Flatten the array in order for the reduce method to work
properly:
var numArr = shrinkLog.getRange(row+3,4,5).flat()
Filter out empty values (blank cells) to get the correct sum:
var numArr = shrinkLog.getRange(row+3,4,5).flat().filter(row=>row!="")
Solution:
Replace that:
var numArr = shrinkLog.getRange(row+3,4,5).getValues();
with
var numArr = shrinkLog.getRange(row+3,4,5).flat().filter(row=>row!="");
for (var i=0; i < arrTarget.length; i++){
//find Row
var row = arrSource.indexOf(arrTarget[i]);
var numArr = shrinkLog.getRange(row+3,4,5).flat().filter(row=>row!="");
//add units in an array
var sum = numArr.reduce(function(a,b){return a+b;},0);
//execute
var testsheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("test Sheet");
testsheet.getRange(i+1,1,1,1).setValue(sum);
}
You could run a .map on your array before and replace any null values with 0.
var sum = numArr
.map(e => e === null ? 0 : e)
.reduce(function(a,b){return a+b;},0);
This question already has answers here:
Creating array of length n with random numbers in JavaScript
(6 answers)
Closed 5 years ago.
const array = new Array(10);
array.fill('hi');
console.log(array);
Using Array::fill to populate a value on the whole array or part of the array.
I have a string generator function that generates a random string.
const getString = () => Math.random().toString(36).replace(/[^a-z]+/g, '');
console.log(getString())
console.log(getString())
console.log(getString())
I want to fill the array with different values by executing the string generator function each time .
It cannot done by one line in fill , however, I found a workaround leveraging the signature of fill : arr.fill(value[, start = 0[, end = this.length]])
const getString = () => Math.random().toString(36).replace(/[^a-z]+/g, '');
const array = new Array(10);
for (var i=0; i < array.length;i++ ) {
array.fill(getString(), i, i + 1);
}
console.log(array);
Does fill supports callbacks that can be executed each iteration to generate different values ?
If no, what is the alternative ?
We can reach the same result in one line combining map and fill :
array.fill().map(getString)
const getString = () => Math.random().toString(36).replace(/[^a-z]+/g, '');
const array = new Array(10);
console.log(array.fill().map(getString))
I have only been learning javascript for 2 weeks, so apologies if my question seems weird/doesn't make sense. I'm learning the basics of arrays, and to help me learn I like to practise and play around with the code but I can't seem to figure this one out.
I've created a simple function, and wanting to call upon the function to calculate the sum of variables in an array. Here is my code below:
//functions
function simpleCalc (a,b) {
var result = a + b;
return result;
}
//array
var myArray = [12,567];
//final calculation
var total = simpleCalc([0],[1]);
alert("The total is " + total);
Can anyone please shed any light as to how I input the numbers "12" and "567" into the function parameters? The result here as it stands outputs to "01"
Thanks
You have two options:
Your option but, it is very limited to only two values.
You need to pass reference to your array elements like so (myArray[0], myArray[1])
Create new function - let's call it sumValuesInArray(), pass an array and calculate all values inside an array using for loop.
See working example here:
//functions
function simpleCalc (a,b) {
var result = a + b;
return result;
}
//array
var myArray = [12,567];
//final calculation
var total = simpleCalc(myArray[0],myArray[1]);
//alert("The total is " + total);
// OR
function sumValuesInArray(array) {
var total = 0;
for(i = 0; i < array.length; i++) {
var element = array[i];
total += element;
}
return total;
}
console.log(sumValuesInArray(myArray));
You don't specify the array but only indexes :
var total = simpleCalc([0],[1]);
So, it passes two array objects : [0] and [1].
The concatenation of them here :
var result = a + b;
has as result the 01 String.
To pass the two first elements of myArray, try it :
var total = simpleCalc(myArray[0],myArray[1]);
You need to access the array values by index. You do this using the brackets WITH the name of the array. If you pass the brackets with numbers inside, you're creating new arrays.
It should be:
var total = simpleCalc(myArray[0],myArray[1]);
This question already has answers here:
How to keep an Javascript object/array ordered while also maintaining key lookups?
(2 answers)
Closed 7 years ago.
I have got a function which retrieves an object.
This object has a property and a value. The property is numeric and starts at "-30" all the way up to "50"
The problem is that when I loop through this object the browser seems to order it starting at "0" instead of starting at the initial property of "-30"
I need to make sure the order is exactly the same as the object.
var colorOj = {
"-30":"#111","-29":"#131313", ..etc.., "0":"#333", ..etc..,
"50":"#555"
}
function makeList(object){
for (var i in object) {
console.log(i); // Returns 0,1,2,3,4,5
// I need a return of -30,-29,-28,..., 0, 1, 2 ...
}
}
makeList(colorObj);
As suggested by #Teemu, properties are not stored in any specific order. But you can print them in any order using specific sort function accordingly.
Code
var obj = {};
for (var i = 5; i > -5; i--) {
obj[i * 10] = i * 10;
}
// Sort and get all keys...
var keys = Object.keys(obj).sort(function(a, b) {
return parseInt(a) - parseInt(b);
});
console.log(keys)
// Loop over keys to print values of each property
keys.forEach(function(item) {
console.log(item, obj[item]);
})
You can do something like this maybe:
var colorOj = {
"-30":"#111","-29":"#131313", "0":"#333",
"50":"#555"
};
var keys = Object.keys(colorOj).sort(function(a,b){return a - b})
for(var i = 0; i < keys.length;i++){console.log(keys[i])}
This way you can get every key in the object. Then sort it however you like(the sort function in javascript can take a compare function as a parameter look -> https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort)
This question already has answers here:
Closed 11 years ago.
Possible Duplicates:
JavaScript: Getting random value from an array
How can I choose an object key at random?
suppose we have an array like this:
var MrArray = new Array(5);
MrArray['one']='oneValue';
MrArray['two']='twoValue';
MrArray['three']='threeValue';
MrArray['four']='fourValue';
MrArray['five']='fiveValue';
ok?
the Array is associated.
and we have string key and string value.
now! how can i pick a random value from that?
Edit:i want to use like this:
Array Key Here
Regards
Sam
Using the method described here we can create the following function:
function randomKey(obj) {
var ret;
var c = 0;
for (var key in obj)
if (Math.random() < 1/++c)
ret = key;
return ret;
}
It returns a random key, so to get a random value from MrArray, do this:
var value = MrArray[randomKey(MrArray)];
jsPerf benchmark comparing the speed of this and the other answer.
Here:
function fetch_random(obj) {
var temp_key, keys = [];
for(temp_key in obj) {
if(obj.hasOwnProperty(temp_key)) {
keys.push(temp_key);
}
}
return obj[keys[Math.floor(Math.random() * keys.length)]];
}
Src: How can I choose an object key at random?