I have an array with 100 elements, I want to take an element from 10th to 15th (10, 11, 12, 13, 14, 15), than from 20th to 25th, than from 30th to 35th, from 40th to 45th and from 50th to 55th, so I always have a gap= 4 and store to a new 2D value. I found out how to store to 2D array, but how could I make this gap?
this is how I could make a chunk of size 6 (because I always need first six element of "decade")
var newArr = [];
while(arr.length) newArr.push(arr.splice(0,6));
or
function splitArray(array, part) {
var tmp = [];
for(var i = 0; i < array.length; i += part) {
tmp.push(array.slice(i, i + part));
}
return tmp;
}
console.log(splitArray(m1, 6));
But first of all I have to make a new array of elements (10-15, 20-25 and so on...). How could I do this?
Your function needs a separate parameter for the stride and the size of each part. It uses the stride when incrementing the for loop variable, and the size when taking the slice.
function splitArray(array, stride, size) {
var tmp = [];
for(var i = 0; i < array.length; i += stride) {
tmp.push(array.slice(i, i + size));
}
return tmp;
}
var m1 = [];
for (var i = 0; i < 100; i++) {
m1.push(i);
}
console.log(splitArray(m1, 10, 6));
A generator function removes the need to store intermediate results. Introducing an offset argument allows you to skip the first five values 0, 1, 2, 3, 4, 5:
function* splitArray(array, stride, size, offset = 0) {
for (let i = offset; i < array.length; i += stride) {
yield array.slice(i, i + size);
}
}
// Example:
const array = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25];
console.log(...splitArray(array, 10, 6, 10));
Apart from those particularities, this implementation is identical to Barmar's answer.
Related
can anyone tell me what is this code for?
especially this line of code, I can't understand this line
ctr[arr[i] - 1]++;
function array_element_mode(arr) {
var ctr = [],
ans = 0;
for (var i = 0; i < 10; i++) {
ctr.push(0);
}
for (var i = 0; i < arr.length; i++) {
// what is this code for??
ctr[arr[i] - 1]++;
if (ctr[arr[i] - 1] > ctr[ans]) {
ans = arr[i] - 1;
}
}
return ans + 1;
}
console.log(array_element_mode([1, 2, 3, 2, 2, 8, 1, 9]))
I believe that this function is supposed to return the mathematical mode of an array.
I just added/fixed some variable names to your function. This is still a terrible implementation but I'm hoping that the edits will make what it does more clear to you.
function array_element_mode2(arr) {
var center = [],
mode = 0;
for (let i = 0; i < 10; i++) {
center.push(0);
}
for (let i = 0; i < arr.length; i++) {
const priorElementOfArr = arr[i] - 1;
center[priorElementOfArr]++;
if (center[priorElementOfArr] > center[mode]) {
mode = priorElementOfArr;
}
}
return mode + 1;
}
I renamed the varibles and splitted ctr[arr[i] - 1]++; into two lines. This functions is supposed to find the number which appears most in a given array of integers.
But it wont work if two or more integers appear the same number of times and if the array contains 0.
/*
* Goal: Find the number which appears most in a given array of integers
* Solution: In the ctr array store the number apperences in the following way
* ctr[0] appearances of "1" in the array
* ctr[1] appearances of "2" in the array
* ctr[2] appearances of "3" in the array
* ...
*/
function array_element_mode(arr) {
var ctr = [],
ans = 0;
// fill the ctr array with nulls
for (var i = 0; i < 10; i++) {
ctr.push(0);
}
for (var i = 0; i < arr.length; i++) {
//////////// here the ctr[arr[i] - 1]++; is splitted into 2 lines
// for each array member "find" the correct index to increase
const convertArrayMemberToIndexForCtr = arr[i] - 1;
// increase the correct index by one
ctr[convertArrayMemberToIndexForCtr]++;
///////////
// check if the increased index if larger then current answer and if so
// store it as the new result
if (ctr[convertArrayMemberToIndexForCtr] > ctr[ans]) {
ans = convertArrayMemberToIndexForCtr;
}
}
// return the result, but not the index we created before (on line 25), but the real number that is in the array (add the +1 we subtracted before)
return ans + 1;
}
console.log('working example');
console.log(array_element_mode([1, 2, 3, 2, 2, 8, 1, 9]));
console.log('this wont work, it shows that "3" is the result, ignoring the "2"');
console.log(array_element_mode([3, 3, 3, 2, 2, 2, 5, 9]));
console.log('this wont work as index arr[i] - 1 would then be 0-1=-1');
console.log(array_element_mode([0, 1, 1, 0, 0, 4, 5, 9]));
console.log('this wont work, all integers are only once in the array');
console.log(array_element_mode([1, 2, 3, 4, 5, 6, 7, 8]));
I think this function is to find out which element has the most number in the array
ctr[arr[i] - 1]++:In order to count
Would like to create a two dimensional m x n array in javascript, based on the number of columns, that is inputed as an argument in my function, the rows would be created from another argument which would be an array.
What I look to achieve - Desired Result:
var arr = [0,1,2,3,4,5,6,7,8,9]
function TwoDimensionalArray(numRows, numCols) {
//Magic happens here!
}
TwoDimensionalArray(arr, 4);
As you can see the is a 3 x 4 matrix below and a desired result
[[0,1,2,3], [4,5,6,7],[8,9]]
The input size doesn't make the difference, the number of columns is the key factor and the determinant factor.
What I have currently - Not Desired Result:
var arr = [0,1,2,3,4,5,6,7,8,9,10,11,12,13]
function TwoDimensionalArray(numRows, numColumns) {
var twoD = [];
for (var row = 0; row < numRows.length; ++row) {
var cardIndex = numRows[row]
// console.log(numRows[row]);
var columns = [];
for(var j =0; j < numColumns; ++j) {
columns[j] = cardIndex;
}
twoD[cardIndex] = columns;
}
return twoD;
};
var matrixTwoD = TwoDimensionalArray(arr, 4);
console.log(matrixTwoD);
console.log(matrixTwoD[0][0]);
console.log(matrixTwoD[0][1]);
console.log(matrixTwoD[0][2]);
console.log(matrixTwoD[0][3]);
My current code creates an array that repeats each of the elements 4 times each until the number 13 with a column size of 4: [[0,0,0,0], [1,1,1,1]....[13,13,13,13]]
Maybe am doing something wrong in my for loop or not approaching the problem correctly. But anything to point me in the right direction to get the above desire result.
Bouns
Also would anyone also be kinda to point me to additional resources for matrix algebra pertaining to this sort of problem and anything in general that would help for self study.
Thanks a bunch!
Keep it simple, slice the input Array into sections of numCols length
function TwoDimensionalArray(arr, numCols) {
var arr2d = [],
i;
if (numCols) // safety first!
for (i = 0; i < arr.length; i += numCols)
arr2d.push(arr.slice(i, i + numCols));
return arr2d;
}
if (numCols) prevents an infinite loop in the case numCols was not provided or is 0
for (i = 0; i < arr.length; i += numCols) counts up from 0 in numCols, e.g. i = 0, 4, 8, 16, ... until we reach a number greater than arr.length
arr.slice(i, i + numCols) creates a sub-Array of Array starting from (including) index i and ending at (excluding) index i + numCols, i.e. we get a numCols long Array starting with the item at index i of arr
arr2d.push appends a new item to the end of arr2d
Putting all these together, we can see that we are building a new Array arr2d from sections of the Array arr
calculate columns required and then use slice method of array.
start index = (numColumns * i)
end index = numColumns * (i + 1)
var arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
function TwoDimensionalArray(numRows, numColumns) {
var columns = [];
for (var i = 0; i !== Math.ceil(numRows.length / numColumns); i++) {
columns[i] = numRows.slice((numColumns * i), numColumns * (i + 1))
//console.log((numColumns * i) + " " +numColumns * (i + 1))
}
return columns;
};
var matrixTwoD = TwoDimensionalArray(arr, 4);
console.log(matrixTwoD);
console.log(matrixTwoD[0][0]);
console.log(matrixTwoD[0][1]);
console.log(matrixTwoD[0][2]);
console.log(matrixTwoD[0][3]);
I am rather new to JS and I was working on a problem that asked to split an array (first argument) into groups the length of size (second argument) and returns them as a multidimensional array.
I got the problem to work right for all test cases but it suggested using the array `push()` method. I tried it multiple times and couldn't ever get it to work right. I think I was getting messed up with arrays being by reference. I eventually declared a new Array for each element. I went with a more classic deep copy each element at a time. I Didn't go back and try the `push()` method again. There has to be a more efficient way to do this. I want to write good code. Would love to see better versions please.
Thanks!
function chunk(arr, size) {
var group = 0;
var counter = 0;
var even = false;
var odd = false;
if (arr.length % size === 0) {
group = arr.length / size;
even = true;
} else {
group = Math.ceil(arr.length / size);
odd = true;
}
var newArr = new Array(group);
for (var i = 0; i < group; i++) {
newArr[i] = new Array(size);
}
for (i = 0; i < group; i++) {
for (var j = 0; j < size && counter < arr.length; j++) {
newArr[i][j] = arr[counter++];
}
}
return newArr;
}
chunk(['a', 'b', 'c', 'd'], 2);
Using Array.prototype.slice, the function can be written in a shorter way:
function chunk(array, size) {
var result = []
for (var i=0;i<array.length;i+=size)
result.push( array.slice(i,i+size) )
return result
}
You can try the slice method from the Array object. Here's an idea on how to use it.
var arr = [1, 2, 3, 4, 5, 6];
var newArr = [];
newArr.push(arr.slice(0, arr.length / 2));
newArr.push(arr.length / 2, arr.length);
This is just an shallow implementation but you can use the same concept inside a better written function.
Here's an example function:
var arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14];
function toChunks(arr, size) {
var i = 0,
chunks = [];
for (; i < arr.length; i += size) {
chunks.push(arr.slice(i, i + size););
}
return chunks;
}
toChunks(arr, 2);
Suppose we have an array of variable length, and I want to process it by chunks that are of a maximum length of 100, and do it in the minimum number of chunks. So for an array of length 241, it would be 3 sub arrays of sizes 41, 100, 100 (or 100, 100, 41).
curr_len = arr.length;
offset = curr_len%100;
doSomethingWithSubArray(arr.slice(offset))
for(j = offset; j <= curr_len; j = j+100){
doSomethingWithSubArray(arr.slice(j,j+100))
}
I'm sure there are more elegant ways of doing this, possibly without the special case before the for loop. Any ideas?
I'd expect the last chunk to be of smaller size. The code then would be:
for (var i=0; i<arr.length; i+=100)
doSomethingWithSubArray(arr.slice(i, 100));
This is exactly what my splitBy function does:
Array.prototype.splitBy = function(n) {
/* get: number of items per array
return: array of n-sized arrays with the items (last array may contain less then n) */
for (var r=[], i=0; i<this.length; i+=n)
r.push(this.slice(i, i+n));
return r;
}
Then write only:
arr.splitBy(100).forEach(doSomethingWithSubArray);
use chunk function~
function chunk(a, s){
for(var x, i = 0, c = -1, l = a.length, n = []; i < l; i++)
(x = i % s) ? n[c][x] = a[i] : n[++c] = [a[i]];
return n;
}
console.log(chunk([1,2,3,4,5,6,7,8,9,10], 3));
it's functional style recursive solutions.
no var, no loop, no count, because it's more cleary
var chunk = function(arr, n){
if (arr.length == 0) return [];
var head = arr.slice(0, n), rest = arr.slice(n);
return [head].concat( chunk(rest, n) );
};
console.log(chunk([1,2,3,4,5,6,7,8,9,10], 3));
Not really, using reduce looks like this:
var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
var splitArrays = array.reduce(function(arr, cur, i) {
if (i % 3 === 0) arr.push([]);
arr[i / 3 | 0].push(cur);
return arr;
}, []);
//splitArrays looks like:
//[[1,2,3],[4,5,6],[7,8,9],[10,11]]
More generic function
function splitArray(array, num) {
return array.reduce(function(arr, cur, i) {
if (i % num === 0) arr.push([]);
arr[i / num | 0].push(cur);
return arr;
}, []);
}
Make your doSomethingWithSubArray function accept a starting index and return a next unprocessed index or null if there's no more work. Put this "iterator" in a while loop. Do rest of work that you want to do between chunks (update UI?) right after calling this "iterator" in a while condition.
Say for instance I have the number 12:
var number = 12;
How could I change that number into something like:
var n = [0,1,2,3,4,5,6,7,8,9,10,11,12];
Someone probably has a jQuery shortcut, but here's a plain JavaScript solution:
var num = 12;
var n = [];
for (var i=0; i <= num; i++) {
n.push(i);
}
As a function:
function num2Array(num) {
var n = [];
for (var i=0; i <= num; i++) {
n.push(i);
}
return n;
}
console.log(num2Array(15));
// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
I actually had this function sitting around:
function number_range(beginning, end) {
var numbers = [];
for (; beginning <= end; beginning++) {
numbers[numbers.length] = beginning;
}
return numbers;
}
So if you need to generate more than one of these arrays, it could be useful:
var n = number_range(0, 12);
As for jQuery, well... I don't think that's necessary in this case. (I also don't know of any such function off the top of my head.)
jQuery doesn't have this, but you could use underscore.js:
http://documentcloud.github.com/underscore/#range
_.range([start], stop, [step])
So you could do:
var n = _.range(12);
Or:
var n = _.range(0, 12);
Another JavaScript method
var number = 12, i = 0, n = [];
while( n.push( i++ ), i <= number );
If you need an array just for iterate through you can doing this :
Array(12).fill('');
You just need finding the index from a loop fn to retrieve the current number.