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))
Related
This question already has answers here:
Split array into chunks
(73 answers)
Closed 6 days ago.
This post was edited and submitted for review 6 days ago.
I'm using arrayofArrays[0].push() inside a for loop in order to add an Object to the Array0 inside arrayofArrays.
Now I'd like that when Array0 has reached 2 element, the next element will be pushed to Array1, in order to achieve this situation:
var arrayofArrays = [[Obj0,Obj1],[Obj2,Obj3],[Obj4,Obj5], ...];
Sample code:
var arrayofArrays = [[]];
for(data in Data){
var Obj = {"field1":data[0], "field2":data[1], "field3":data[2] }
arrayofArrays[0].push(Obj); // need to pass to arrayofArrays[1] when arrayofArrays[0] has 2 Obj...
}
(I don't need to split an existing array, I'm adding Object to an array, and want them to split in sub-arrays while adding them)
Here is a functional programming approach to your question to unflatten an array:
const arr = Array.from(Array(6).keys()); // [0, 1, 2, 3...]
let t;
let arrOfArr = arr.map((v, idx) => {
if(idx % 2) {
return [t, v];
} else {
t = v;
return null;
}
}).filter(Boolean);
console.log({
arr,
arrOfArr,
});
Note: Array.from(Array(6).keys()) is just for demo. Replace this with any array of objects you like
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));
This question already has answers here:
Merge keys array and values array into an object in JavaScript
(14 answers)
Closed 1 year ago.
I'm using local storage to get an arrays of strings,
First value attrIds is as follows,
var attrIds = localStorage.getItem('attributeids');
attrIds = JSON.parse(attrIds);
Second value confOptions is as follows,
I want something like this,
144: "5595"
93: "5487"
I have tried creating a loop inside the loop and tried to set the key and value but it's not working. I have also tried to set the single JSON object as key and setting value as '' but couldn't move further with that.
Does anyone have any idea regarding this?
You can accomplish this using a simple for loop, accessing the items from the arrays, and assigning properties to an empty object.
const keys = ['144', '93'];
const values = ['5595', '5487'];
const obj = {};
for (let i = 0; i < keys.length; i++) {
obj[keys[i]] = values[i];
}
console.log(obj); // prints { 144: '5595', 93: '5487' }
Create a nested array and then use Object.fromEntries().
const
a = ["144", "93"],
b = ["5595", "5487"],
c = Object.fromEntries(a.map((v, i) => [v, b[i]]));
console.log(c);
Using a for loop, you could do something like:
var attrIds = localStorage.getItem('attributeids');
attrIds = JSON.parse(attrIds);
confOptions = ["5595", "5487"]
const object = {};
for(let i=0; i<attrIds.length;i++)
object[attrIds[i]] = confOptions[i]
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:
How do you search an array for a substring match?
(15 answers)
Javascript Searching Array for partial string
(2 answers)
Check for Partial Match in an Array
(5 answers)
Closed 3 years ago.
How can I find a match in an array of strings using Javascript? For example:
var str = "https://exmaple.com/u/xxxx?xx=x";
var filter = ["/u","/p"];
if (!str.includes(filter)){
return 1;
}
In the above code I want to search for var str if match this two values of array filter
This should work:
var str = "https://exmaple.com/u/xxxx?xx=x";
var filters = ["/u","/p"];
for (const filter of filters) {
if (str.includes(filter)) {
console.log('matching filter:', filter);
break; // return 1; if needed
}
}
In your array you need to find the element which includes "/u". filter will return an array and will contain only those element which includes u
var x = ["https://exmaple.com/u/xxxx?xx=x", "https://exmaple.com/p/xxxx?xx=x"];
let matched = x.filter(item => item.includes("/u"));
console.log(matched)
Try this:
var x = ["https://exmaple.com/u/xxxx?xx=x","https://exmaple.com/p/xxxx?xx=x"], i;
for (i = 0; i < x.length; i++) {
if(x[i].includes('/u')) {
document.write(x[i]);
}
}
This loops through all the URLs and picks the one that has /u in it. Then it just prints that out.