sort possible options javascript array using fundamental counting principle - javascript
I have 3 arrays which contains different values. and want get possible order options using.
I want to make a variation for my product, so when I select 3 variations, javascript will generate the possible sorting options.
eg:-
colors=['black','red','yellow'];
sizes=['s','m','l','xl','2xl','3xl'];
status=['used','new'];
let array1=['black','red','yellow'];
let array2=['s','m','l','xl','2xl','3xl'];
let array3=['used','new'];
var all=[];
all.push(colors.toString());
all.push(sizes.toString());
all.push(status.toString())
for (var i = 1; i <= 3; i++) {
console.log(option);
}
expecting:
[
'black,s,used',
'black,s,new',
'black,m,used',
'black,m,new',
'black,l,used',
'black,l,new',
'black,xl,used',
'black,xl,new',
'black,2xl,used',
'black,2xl,new',
'black,3xl,used',
'black,3xl,new',
'red,s,used',
'red,s,new',
'red,m,used',
'red,m,new',
'red,l,used',
'red,l,new',
'red,xl,used',
'red,xl,new',
'red,2xl,used',
'red,2xl,new',
'red,3xl,used',
'red,3xl,new',
'yellow,s,used',
'yellow,s,new',
'yellow,m,used',
'yellow,m,new',
'yellow,l,used',
'yellow,l,new',
'yellow,xl,used',
'yellow,xl,new',
'yellow,2xl,used',
'yellow,2xl,new',
'yellow,3xl,used',
'yellow,3xl,new',
]
I want to use product variation when a person chooses the 3 variations I mentioned above.
This is how you calculate variations for your products
let colors=['black','red','yellow']; let
sizes=['s','m','l','xl','2xl','3xl']; let status=['used','new']; let
variations = [] for(let k=0;k<colors.length;k++){
for(let i=0; i< sizes.length;i++){
for (let j=0; j<status.length;j++){
variations.push(`${colors[k]}-${sizes[i]}-${status[j]}`)
}
} }
console.log(variations)
Related
How can I get sum of values from different divs with the same class using only javascript without libraries?
let sum = []; for(i=1; i< 16; i++ ) { document.getElementsByClassName(`number${i}`).forEach(function() { sum += parseFloat(this.innerText()); }); } I have built a dynamic flexbox table which has students names and their marks in each for every day. there are 15 students as you can guess. Now what I am trying to do is to calculate the sum of all the marks across each row upon clicking update button. I have assigned number1, ... number15 classes for cells in the same row(number1 first row number2 second row, etc). So far I have managed to do this but it does not work. Remember I don't want to use jquery, this needs to be done with javascript only.Any help would be appreciated.(I have an add button which creates a new day onclick with the same classes, so number1, number2 classes represent arrays of divs with marks as textnodes.)
First you have to initialize an Array from the HTMLCollection by using the Array.from() static method, if you want access to the array methods in ECMAScript. Then you can use reduce() to accumulate the sum from each class name, and push() it into the sum array: const sum = []; for (i = 1; i <= 15; i++) { const innerSum = Array.from( document.getElementsByClassName(`number${i}`) ).reduce( (acc, el) => acc + parseFloat(el.innerText), 0 ); sum.push(innerSum); }
You should be able to accomplish this by adding a variable within the loop. This will reset for each student, sum their grades, then add it to your sum array: let sum = []; for(i=1; i< 16; i++ ) { let studentSum = 0; document.querySelectorAll(`.number${i}`).forEach(function(ele) { studentSum += parseFloat(ele.innerText()); }); sum.push(studentSum) } Edit: As noted, you can't use document.getElementsByClassName(..).forEach try document.querySelectorAll(..).forEach instead.
Not sure if that is what you asked for but try to see if that works for you: const sum = []; const students = document.querySelectorAll('.student'); for(student of students) { sum.push(parseFloat(student.innerText)); } console.log(sum); <div class="student">1</div> <div class="student">2</div> <div class="student">3</div>
Randomly selecting unique items from an array with Javascript
I know that there have been a lot of similar questions and I went through most of them. The code that is closest to what I'm trying to achieve is this one. I have a list of people in each column (which represent a day). for the sake of this question let's assume it's 8 people in each column. I need to randomly select 5 unique people names. I've used splice() to delete the selected item from the array to make sure that it is not selected twice. I'm new to the coding and I think I'm doing some basic mistake as the splice works for the 1st loop and then the array goes back to the original one. Can you, please, help to identify my mistake? for (var x = 0; x < 5; x++) { var sourceArray = ss.getRange(49,j+5,8,1).getValues(); var gg = Math.floor(Math.random()*sourceArray.length); var pickedHLA = sourceArray[gg]; sourceArray.splice(gg, 1); var HLAselect = ss.getRange(30+x,j+5,1,1) HLAselect.setValue(pickedHLA);
In your for loop you are redefining the sourceArray during each iteration - you need to define this outside the loop, then do your work to randomly select and remove from the array: var sourceArray = ss.getRange(49,j+5,8,1).getValues(); //establish full list of people for (var x = 0; x < 5; x++) { var gg = Math.floor(Math.random()*sourceArray.length); //get random index var pickedHLA = sourceArray[gg]; //get random person via random index sourceArray.splice(gg, 1); //remove random person from full list of people var HLAselect = ss.getRange(30+x,j+5,1,1) HLAselect.setValue(pickedHLA); }
The way you do this is actually quite simple, all it requires a few lines of code: var arr = ["Cheese", "Purple", "List", "1", "2", "3", "4", "5"]; function random() { var randomNumber1 = parseInt(Math.random() * arr.length); var random = arr[randomNumber1]; alert(random); } <button onClick="random()">Click Me</button> There you go!
map box js; hide and show label
I've never worked with JavaScript before. I'm trying to create a map where different layers can be hidden per users preference. I came across the helpful example on map box showing the exact code at https://www.mapbox.com/mapbox-gl-js/example/toggle-layers/. Now, my problem is, because I have numerous point layers of different magnitudes, I was forced to create several layers and filter them based on the desired attribute so each points appearance reflects that specific magnitude. However, I want all these points to be organized into years, so I grouped the layers. So all my layer names look something like this (2006_mag2,2006_mag8,2010_mag3...). However, I want the hide/show option to show layers based on years. So I was thinking I could do some sort of operator like we use in sql (i.e. '2006%' or a LIKE operator). Looking at some posts a lot of people use '*' in JavaScript? So this is what it would look like for each layer individually before: var toggleableLayerIds = [ '2006_mag2', '2010_mag3' ]; for (var i = 0; i < toggleableLayerIds.length; i++) { var id = toggleableLayerIds[i]; } and this is my botched attempt at trying to group a number of the layers together: var toggleableLayerIds = [ '2006.*', '2008.*' ]; for (var i = 0; i < toggleableLayerIds.length; i++) { var id = toggleableLayerIds[i]; } Any guidance you guys can provide will be greatly appreciated.
You could try to use loops with regex to group layerIds by date. Sorry I changed the name of your variables. This will get you an object with layerIds grouped by date. var layerIds = [ '2006_mag2', '2010_mag3', '2006_mag8', '2006_mag1', '2008_mag2']; var dates = ['2006', '2010']; var groupedLayers = {}; //init your object to have a member for each date //this could be done inside the loops below by testing if the array exists before pushing the matching layerId for (var i=0; i < dates.length; i++) { groupedLayers[dates[i]] = []; } //loop over your layerIds to match with the RegExp for (var i=0; i < layerIds .length; i++) { for (var j=0; j < dates.length; j++) { var searchPattern = new RegExp('^' + dates[j]); if (searchPattern.test(layerIds[i])) { groupedLayers[dates[j]].push(layerIds[i]); } } } console.log(groupedLayers) Please tell me what exact result you need so I could help you more.
Push multi-dimension array into another array
I have an multi-dimension array that i'm iterating through. Is there a way to put the contents of the array into a new multi-dimension array creating a new MDA? For example, the following code puts all indices of the original array into the new candies array if there's a match. Currently i'm doing candies.push([product[0],product[1], etc...]); I'm just trying to see if there's a faster/cleaner way to get that in there. I tried: candies.push(product); but that didn't work. Here's the code i'm currently using var sel = 'candy'; var candies = []; for(var i = 1; i < products.length; i++) { var product = products[i]; for(var j = 0; j < product.length; j++) { if(sel==product[11]){ candies.push([product[0],product[1],product[2],product[3],product[4],product[5],product[6],product[7],product[8],product[9],product[10],product[11],product[12]]); } break; } }
A cleaner way of writing below line: candies.push([product[0],product[1],product[2],product[3],product[4],product[5],product[6],product[7],product[8],product[9],product[10],product[11],product[12]]); is: candies.push(product.slice(0,13)]); Sample example JSFiddle is here. Best of luck. (Mark this as answer if it serves your need.)
String to arrays
I have below String that needs to be divided into multiple array after 5 comma separated values. Then I need to put each array values to textbox values using script. I tried the below code to split and assign to array but not working. Is there any way this can be resolved? <%=ab%> is the JavaScript variable that contains the below code. [768.234.232, 768.234.232, 574,10-10-2012, 10-10-2012, 768.234.232, 768.234.232, 987, 10-10-2012, 10-10-2012] function functionOne() { var list = "<%=ab%>"; var ab = new Array(); var i = 0; for (i = 0; i < 10; i++) { ab[i] = list.split(",", 3); alert(ab[i]); } }
"needs to be divided into multiple array after 5 comma seperated values" You seem to be saying that the result should be one array with five values in it and then a second array with the next five values in it, etc. If so, you can do the following: var list = "<%=ab%>"; list = list.slice(1,-1); // remove the enclosing [] var allValues = list.split(/\s*,\s*/); // split on comma with optional whitespace var a = []; for (var i = 0; i < allValues.length; i+=5) { a.push( allValues.slice(i, i+5<=allValues.length ? i+5 : allValues.length) ); } After running the above, a will be array that contains other arrays. a[0] is an array of the first five items, so, e.g., a[0][2] is the third item. a[1] is an array of the next five items. If there were more than ten items in the original list then a[2] would be an array of the next five, etc. If the total number of items is not divisible by five then the last array would hold the remainder. Demo: http://jsfiddle.net/9xAxz/ "Then I need to put each array values to textbox values" Um... does that mean one item per textbox? If so, why did you want to divide up after five values? Do you mean five items per textbox? Either way are you talking about dynamically creating textboxes? If so you can follow the above code with something like this: var tb; for (i = 0; i < a.length; i++) { tb = document.createElement('input'); tb.value = a[i].join(", "); document.body.appendChild(tb); } Demo: http://jsfiddle.net/9xAxz/1/ If I'm completely off base on any of the above, well... think about editing your question to make it clearer. I suppose I should've clarified before answering, but please update the question to show what your desired output is for that input.
function functionOne() { var list = "<%=ab%>".split(/,\s?/g); for (var i = 0; i < list.length; i++) { t = document.createElement('input'); t.type = 'text'; t.value = list[i]; document.body.appendChild(t); } } functionOne(); http://jsfiddle.net/WJPHt/1/