This question already has answers here:
Split array into chunks
(73 answers)
Closed 8 years ago.
I am new to javascript. I have a list of 500 or more items. I need split this array into sub arrays each containing 20 items. i.e 25 arrays if there are exactly 500 items and each array containing 20 items. I created 25 arrays like below:
var firstSet=[];
var secondSet=[];
.....
And i populate each of this array using the for loop. In javascript how can I make it programmatically since the main list can return more than 500 items in future and each sub array should be configured for more than 20 items in future. What is the best solution to fix this situation?
As comments say, you should split it with a 2 dimentional array:
var mainArray=[1,2,3,4,5,6,7,8,9,10];
function splitArray(arr,qty){
var mainArr=[], subarr=[];
for(var i=0;i<arr.length;i++){
subarr.push(arr[i]);
if( ((i+1) % qty == 0) || i+1==arr.length){
mainArr.push(subarr);
subarr=[];
}
}
return mainArr;
}
console.log(splitArray(mainArray,2));
This creates 1 array with 5 indexes. In each index, you have an array of 2 elements. So it groups it in [1,2], [3,4], [5,6], [7,8], [9,10]
Use nested loops to create a 2-dimensional array from the original data.
var sets = [];
var items_per_set = 20;
for (var i = 0, outer = 0; i < list.length; i += items_per_set, outer++) {
sets[outer] = [];
var limit = Math.min(list.length, i+items_per_set);
for (j = i; j < limit; j++) {
sets[outer].push(list[j]);
}
}
Related
This question already has answers here:
How to get the difference between two arrays in JavaScript?
(84 answers)
Closed 2 years ago.
First let me say am a novice at Javascript so this may be more obvious than I think. But what I'm trying to do is create a new Javascript array from two existing arrays. My thinking is to create a for loop, test if they are equal and if not push that number into a new array. For example.
var allArr = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20];
var myArr = [7,8,9,10,14,17];
var fnlArr = [];
What I would like to end up with is fnlArr = [1,2,3,4,5,6,11,12,13,15,16,18,19,20];
Something like:
for (n = 0; n < myArr.length; n++){
for (p = 0; p < allArr.length; p++){
if (p!==myArr[n]){
fnlArr.push(p);}
}
}
I was also thinking maybe to grep to see if they are the same???
Any help would be appreciated.
You can use .filter:
const allArr = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20];
const myArr = [7,8,9,10,14,17];
const set = new Set(myArr);
const fnlArr = allArr.filter(e => !set.has(e));
console.log(fnlArr);
This question already has answers here:
How to add same elements to javascript array n times
(4 answers)
Closed 4 years ago.
I've been trying to figure this problem out for a while but I'm at a blank. Here's what I have so far:
var repeatNumbers = function(data) {
var repeated = [];
for ( var x = 0; x < data.length; x++){
var unit = data[x][0]
var quant = data[x][1]
for(var i = quant; i > 0; i--){
repeated.push(unit);
repeated.join(',');
}
return repeated;
}
};
console.log(repeatNumbers([1, 10]));
Basically I'm trying to repeat the first number of the array based off of the second value. Any insight would be greatly appreciated thank you! :)
You don't need to loop over your array if you only have two numbers, where the first number (at index 0) is the number you want to repeat, and the second number is the number of times you want to repeat that number (index 1).
Once you have the number of times you wish to repeat the number, you can simply use a for loop to enter the number into your repeated array that number of times.
See working example below (read code comments for further explanation):
var repeatNumbers = function(data) {
var repeated = []
var toRepeat = data[0]; // get the first number in the array
var times = data[1]; // get the second number in the array
// loop the number of times you want to repeat the number:
for(var i = 0; i < times; i++) {
repeated.push(toRepeat); // push the number you wish to repeat into the repeated array
}
return repeated.join(); // return the joined array (as a string - separated by commas)
}
console.log(repeatNumbers([1, 10]));
If I understand your question correctly, you want the function repeatNumbers() to return an array with the first element in the passed array replicated by the second element in the passed array.
To achieve that, you could do the following:
var repeatNumbers = function(data) {
// Extract the "value" to be repeated, and the "repeated" value
// that will control the number of "value" items in result array
var value = data[0];
var repeated = data[1];
var result = []
// Loop over repeated range, and push value into the result array
for (var i = 0; i < repeated; i++) {
result.push(value);
}
// Result result array
return result;
};
console.log(repeatNumbers([1, 10]));
Or, if you don't need to support IE, a more consise approach would be:
var repeatNumbers = function(data) {
var value = data[0];
var repeated = data[1];
return (new Array(repeated).fill(value));
};
console.log(repeatNumbers([1, 10]));
This question already has answers here:
Split array into chunks of N length [duplicate]
(2 answers)
Closed 5 years ago.
I am trying to build an airport style terminal arrival/departure table view. Trying to make the rows viewable dynamic depending on viewable window.
I have an array that could have any number of rows. Each row is an array itself. I am trying to break up the rows in the array into chunks depending on how much table rows the view can support.
So my question is I'm not sure how to break it up into chunks properly depending on dynamic sizes I want the chunks to be in. I've tried slice and splice but it only adds to the first element in the shortArrays then the rest of the elements are all empty.
INCOMING DATA:
array([array1], [array2], [array3], [array4], [array5], [array6], [array7], [array8], [array9], [array10], [array11], [array12], [array13]), [array14]), [array15]))
OUTGOING DATA:
array([[array1], [array2], [array3], [array4], [array5], [array6], [array7], [array8], [array9], [array10]], [[array11], [array12], [array13], [array14], [array15]]) // 2 rows, row1: 10 arrays, row2: 5 arrays
var jsonData = JSON.parse(data); // data is value returned from ajax
var maxRowsPerTableView = 10; // Hardcoded as an example
var totalTablesToMake = 2; // Hardcoded as an example
var longArray = jsonData;
var shortArrays = [];
var tempCount, doorCount = 0; // Keeps track of which index
for(a = 0; a < totalTablesToMake; a++)
{
temp = [];
for(b = 0; b < maxRowsPerTableView; b++)
{
temp.push(longArray[b + doorCount]);
tempCount = b;
}
doorCount += tempCount;
shortArrays.push(temp);
}
RESULT:
shortArrays([10 elements],[10 elements]) // This isn't actual output, just a visual description so you can see what results I get.
This current code will output: shortArrays with 2 rows, each rows have 10 elements. So let's say there is only 15 elements in the jsonData. The second row in shortArrays will still have 10 elements, but the last 5 will be undefined.
longArray[b + doorCount]
will return undefined if youre out of the arrays bounds. So you either fill in sth else ( an Array for Example)
longArray[b + doorCount]||[];
Or you stop the loop then:
mainloop:for(a = 0; a < totalTablesToMake; a++)
{
temp = [];
for(b = 0; b < maxRowsPerTableView; b++)
{
if(b+a*maxRowsPerTableView>=longArray.length) break mainloop;
temp.push(longArray[b + doorCount]);
tempCount = b;
}
doorCount += tempCount;
shortArrays.push(temp);
}
This question already has answers here:
Get all non-unique values (i.e.: duplicate/more than one occurrence) in an array
(97 answers)
Closed 8 years ago.
I'm like to count the total values in my array but I like to skip the same value
my array example, my real array will have about 1000 values.
json2=[aaa,aaa,aaa,aaa,bbb,bbb,bbb,ccc,ccc,ccc,ccc,ccc,ddd,ddd,ddd,eee,eee,fff];
and i want my count result to be
var countBoxID=6;
i only got
for(i in json2){
countBOXID ++
}
You can make use of this function:
function GetUnique(inputArray)
{
var outputArray = [];
for (var i = 0; i < inputArray.length; i++)
{
if ((jQuery.inArray(inputArray[i], outputArray)) == -1)
{
outputArray.push(inputArray[i]);
}
}
return outputArray;
}
This question already has answers here:
How to randomize (shuffle) a JavaScript array?
(69 answers)
Closed 9 years ago.
I am trying to make a script which is outputting every number from 1-10.
Using a random number generator, in JavaScript.
I want every number to be unique.
Here is an example of what i would like the script to output:
5 9 7 6 1 3 4 8 2 10
This is my attempt:
var test = [];
var amountOfNumbers = 10;
var inArray = false;
var useNumbers = [];
for(var i=0; useNumbers.length<=amountOfNumbers; i++){
var rng = Math.floor((Math.random()*amountOfNumbers)+1);
for(var a=0; a<=test.length; a++){
if(rng == test[a]){
inArray == true;
}
}
if(!inArray){
document.write(rng);
test.push(rng);
useNumbers.push(rng);
}
}
Hope you can help.
for the record I am not interested in jQuery og any other library :)
1) How to fix your code
You have a few errors, among them the fact you don't reset inArray to false and that you don't iterate over the whole test array (use <, not <=). But using a loop to see if you already have the number isn't efficient, it's better to use an object as a map :
var test = [];
var amountOfNumbers = 10;
var useNumbers = {};
for(var i=0; test.length<amountOfNumbers; i++){
var rng = Math.floor((Math.random()*amountOfNumbers)+1);
if(!useNumbers[rng]){
document.write(rng);
test.push(rng);
useNumbers[rng] = true;
}
}
2) How to do it properly
Your algorithm will loop until it is lucky enough to find the remaining numbers. This isn't efficient and isn't predictable. The normal reliable practice is
to generate the array [1..10]
to shuffle it
Generating an array of the integers from 1 to N can be done with a simple loop or in a fancier way :
var arr = Array.apply(0,new Array(N)).map(function(_,i){ return i+1 });
Shuffling an array is usually done with the Fisher-Yates algorithm, for which you'll easily find JS implementations (it's easy to write anyway). A fast (theoretically not guaranteed to work with all future sort implementations) alternative is this one :
arr = arr.sort(function(a,b){ return Math.random()>0.5 });
The whole program
Your approach means to check over all the array in each step, looking if your random number is already inside the array, which means a lot lost time.
Best approach is disordering an ordered array. In each loop, we generate a random number (in the example, a number between 0 and 1) and with a 50% probability we change the item in the current position for other item in a random position (between 0 and the length of the array).
Hope it helps.
function disorder(arg) {
for (var i = 0; i < arg.length; i++) {
if (Math.random() < 0.5) {
var aux = arg[i];
var rndPos = Math.floor(Math.random()) * arg.length;
arg[i] = arg[rndPos];
arg[rndPos] = aux;
}
}
return arg;
}
var myArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var myNewArray = disorder(myArray);
myNewArray.forEach(function(item) {
console.log(item);
});