Recursion is skipping values - javascript

I'm trying to assign/place a set of numbers randomly within a new array as a pair: [1,2,3,4,5,6,7,8] should equal [[1,1],[8,8],[3,3],[7,7],[2,2],[4,4],[5,5],[6,6]]
let numbers = [1,2,3,4,5,6,7,8]
let arrayToBeFilled = [];
function assign(num) {
let randomNumber = Number(Math.floor((Math.random() * 8)));
if(arrayToBeFilled[randomNumber] == null ) {
arrayToBeFilled[randomNumber] = [num, num] ;
} else if (arrayToBeFilled[randomNumber] == Array) {
return assign(num);
} else {
console.log('Trying a new number');
}
}
for (num in numbers) {
assign(Number(num));
}
console.log(arrayToBeFilled);
return arrayToBeFilled;
Returns the array but with values missing where the recursion should have filled the array (what I'm expecting at least). See <1 empty item>.
Trying a new number
Trying a new number
Trying a new number
[ [ 0, 0 ], [ 7, 7 ], [ 5, 5 ], <1 empty item>, [ 2, 2 ], [ 1, 1 ] ]
Anyone have any idea why this is happening??

I made some edits to your code:
/* prefer functions instead of global variables */
function main() {
let numbers = [1, 2, 3, 4, 5, 6, 7, 8]
let arrayToBeFilled = [];
for (num of numbers) { /* Use 'for...of' syntax for array iteration */
assign(Number(num), arrayToBeFilled);
}
return arrayToBeFilled
}
function assign(num, arr) {
const randomNumber = Number(Math.floor((Math.random() * 8)));
if (arr[randomNumber] == null) {
arr[randomNumber] = [num, num];
} else if (Array.isArray(arr[randomNumber])) { /* Proper way to check if element is an Array type */
return assign(num, arr);
} else {
return []
}
}
console.log(main());

Here's my take. The beauty of this is of course the abstraction in form of the shuffle function which works on all arrays, and can be put away into a utility sub file.
function shuffle(a) {
// you can replace this with "let n = a" if you don't care about
// the incoming array being altered
let n = [...a];
for (let i = n.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[n[i], n[j]] = [n[j], n[i]];
}
return n;
}
let numbers = [1,2,3,4,5,6,7,8];
console.log( shuffle( numbers ).map( n => [n,n] ) );

You could create function that will randomize elements and return array of the nth length for each element using while loop.
let numbers = [1, 2, 3, 4, 5, 6, 7, 8]
function randomize(data, n) {
const result = [];
data = data.slice();
while (data.length) {
const pos = Math.floor(Math.random() * data.length);
const el = data.splice(pos, 1).pop();
result.push(Array.from(Array(n), () => el));
}
return result;
}
console.log(randomize(numbers, 2))
console.log(randomize(numbers, 4))

Try the following:
function assign(num) {
let randomNumber = Number(Math.floor((Math.random() * 8)));
if(arrayToBeFilled[randomNumber] == null ) {
arrayToBeFilled[randomNumber] = [num + 1, num + 1] ;
} else {
assign(num);
}
}
You had an else in the code which was skipping one place in the array to be filled

NON-REPEATING random numbers (https://jsfiddle.net/th3vecmg/2/)
let numbers = [1, 2, 3, 4, 5, 6, 7, 8]
let arrayToBeFilled = [];
function assign(numbers, i, size) {
if (i < size) {
assign(numbers, ++i, size);
}
var randomNumber = numbers[Math.floor(Math.random() * numbers.length)];
arrayToBeFilled.push([randomNumber, randomNumber]);
numbers.splice(numbers.indexOf(randomNumber), 1);
}
assign(numbers, 0, numbers.length - 1)
console.log(arrayToBeFilled);
REPEATING random numbers (https://jsfiddle.net/th3vecmg/3/)
let numbers = [1, 2, 3, 4, 5, 6, 7, 8]
let arrayToBeFilled = [];
function assign(numbers, i) {
let randomNumber = Number(Math.floor((Math.random() * 8)));
arrayToBeFilled[i] = [randomNumber, randomNumber];
if (i < numbers.length - 1) {
assign(numbers, ++i);
}
}
assign(numbers, 0)
console.log(arrayToBeFilled);

Related

Sum of similar value in n X n dimensional array with n^2 complexity

Given an array [[1, 7, 3, 8],[3, 2, 9, 4],[4, 3, 2, 1]],
how can I find the sum of its repeating elements? (In this case, the sum would be 10.)
Repeated values are - 1 two times, 3 three times, 2 two times, and 4 two times
So, 1 + 3 + 2 + 4 = 10
Need to solve this problem in the minimum time
There are multiple ways to solve this but time complexity is a major issue.
I try this with the recursion function
How can I optimize more
`
var uniqueArray = []
var sumArray = []
var sum = 0
function sumOfUniqueValue (num){
for(let i in num){
if(Array.isArray(num[i])){
sumOfUniqueValue(num[i])
}
else{
// if the first time any value will be there then push in a unique array
if(!uniqueArray.includes(num[i])){
uniqueArray.push(num[i])
}
// if the value repeats then check else condition
else{
// we will check that it is already added in sum or not
// so for record we will push the added value in sumArray so that it will added in sum only single time in case of the value repeat more then 2 times
if(!sumArray.includes(num[i])){
sumArray.push(num[i])
sum+=Number(num[i])
}
}
}
}
}
sumOfUniqueValue([[1, 7, 3, 8],[1, 2, 9, 4],[4, 3, 2, 7]])
console.log("Sum =",sum)
`
That's a real problem, I am just curious to solve this problem so that I can implement it in my project.
If you guys please mention the time it will take to complete in ms or ns then that would be really helpful, also how the solution will perform on big data set.
Thanks
I would probably use a hash table instead of an array search with .includes(x) instead...
And it's also possible to use a classical for loop instead of recursive to reduce call stack.
function sumOfUniqueValue2 (matrix) {
const matrixes = [matrix]
let sum = 0
let hashTable = {}
for (let i = 0; i < matrixes.length; i++) {
let matrix = matrixes[i]
for (let j = 0; j < matrix.length; j++) {
let x = matrix[j]
if (Array.isArray(x)) {
matrixes.push(x)
} else {
if (hashTable[x]) continue;
if (hashTable[x] === undefined) {
hashTable[x] = false;
continue;
}
hashTable[x] = true;
sum += x;
}
}
}
return sum
}
const sum = sumOfUniqueValue2([[1, 7, 3, 8],[[[[[3, 2, 9, 4]]]]],[[4, 3, 2, 1]]]) // 10
console.log("Sum =", sum)
This is probably the fastest way...
But if i could choose a more cleaner solution that is easier to understand then i would have used flat + sort first, chances are that the built in javascript engine can optimize this routes instead of running in the javascript main thread.
function sumOfUniqueValue (matrix) {
const numbers = matrix.flat(Infinity).sort()
const len = numbers.length
let sum = 0
for (let i = 1; i < len; i++) {
if (numbers[i] === numbers[i - 1]) {
sum += numbers[i]
for (i++; i < len && numbers[i] === numbers[i - 1]; i++);
}
}
return sum
}
const sum = sumOfUniqueValue2([[1, 7, 3, 8],[[[[[3, 2, 9, 4]]]]],[[4, 3, 2, 1]]]) // 10
console.log("Sum =", sum)
You could use an objkect for keeping trak of seen values, like
seen[value] = undefined // value is not seen before
seen[value] = false // value is not counted/seen once
seen[value] = true // value is counted/seen more than once
For getting a value, you could take two nested loops and visit every value.
Finally return sum.
const
sumOfUniqueValue = (values, seen = {}) => {
let sum = 0;
for (const value of values) {
if (Array.isArray(value)) {
sum += sumOfUniqueValue(value, seen);
continue;
}
if (seen[value]) continue;
if (seen[value] === undefined) {
seen[value] = false;
continue;
}
seen[value] = true;
sum += value;
}
return sum;
},
sum = sumOfUniqueValue([[1, 7, 3, 8], [3, 2, 9, 4], [4, 3, 2, 1]]);
console.log(sum);
Alternatively take a filter and sum the values. (it could be more performat with omitting same calls.)
const
data = [[1, 7, 3, 8], [3, 2, 9, 4, 2], [4, 3, 2, 1]],
sum = data
.flat(Infinity)
.filter((v, i, a) => a.indexOf(v) !== a.lastIndexOf(v) && i === a.indexOf(v))
.reduce((a, b) => a + b, 0);
console.log(sum);
You can flatten the array, filter-out single-instance values, and sum the result:
const data = [
[ 1, 7, 3, 8 ],
[ 3, 2, 9, 4 ],
[ 4, 3, 2, 1 ]
];
const numbers = new Set( data.flat(Infinity).filter(
(value, index, arr) => arr.lastIndexOf(value) != index)
);
const sum = [ ...numbers ].reduce((a, b) => a + b, 0);
Another approach could be the check the first and last index of the number in a flattened array, deciding whether or not it ought to be added to the overall sum:
let sum = 0;
const numbers = data.flat(Infinity);
for ( let i = 0; i < numbers.length; i++ ) {
const first = numbers.indexOf( numbers[ i ] );
const last = numbers.lastIndexOf( numbers[ i ] );
if ( i == first && i != last ) {
sum = sum + numbers[ i ];
}
}
// Sum of numbers in set
console.log( sum );

How do I write a function that returns the first 5 positive even numbers?

var myArr = [1,2,3,4,5,6,7,8,9,10];
function even(num) {
var newArr = [];
for (var i=1; i<num.length; i++) {
if (num[i] % 2 === 0) {
newArr.push(num[i]);
}
}
return newArr;
}
console.log(even(myArr));
My function throws an exception when called. How can I rewrite or refactor the above code to return the first 5 positive numbers?
You can create it this way.
var myArr = [1,2,0,3,4,-6,5,-3,88,21,-6,5,6,7,8,9,10];
let evens = myArr.filter(x => x > 0 && x % 2 == 0).slice(0, 5);
console.log(evens)
First off, your code appears to work. Can you give an example of the error that is occurring? Second off, if you want a function that returns an array of the first n positive, even integers, you can write something like this.
function firstEven(count) {
var response = []; // Create the response list
for(var i=0;i<count;i++) { // Loop for number of even numbers you want
response.push((i + 1) * 2); // *2 skips every two numbers, and +1 shifts the number to even
}
return response
}
However, if you want to just filter out all odd numbers from an array, you can do the following.
var myArr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var myEvens = myArr.filter(function(myNum) { // Filter runs the function for every value in the array, and (if the function returns false) it removed that value
return (myNum % 2) == 0;
});
Feel free to ask if you have any questions!
2 others differnts ways
const myArr = [1,2,3,4,-6,5,-3,88,21,-6,5,6,7,8,9,10];
const even_1 = arr => arr.filter(x=>(x>=0 && !(x&1))).slice(0,5)
const even_2 = arr =>
{
let r = []
for(x of arr)
if (x>=0 && !(x&1)) // test2 = boolean AND on bit zero
{
r.push(x);
if (r.length >= 5) break;
}
return r
}
console.log('even 1:', even_1(myArr).join(','))
console.log('even 2:', even_2(myArr).join(','))
One suggestion:
var myArr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];
function even(numbersArray) {
var first5EvenNums = [];
for (const num of numbersArray) {
if (first5EvenNums.length >= 5) break;
if (num % 2 === 0) {
first5EvenNums.push(num);
}
}
return first5EvenNums;
}
console.log(even(myArr));
<script src="//ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<div id="test"></div>
<script>
var myArr = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];
function even(num){
var newArr = [];
for (var i=1; i<num.length; i++){
if (num[i] % 2 === 0)
{
newArr.push(num[i]);
if(newArr.length == 5){
return newArr;
}
}
}
return newArr;
};
$("#test").text(even(myArr));
</script>
This return first 5 positive number in array.

Why does my for loop only return the first result to an array in JavaScript?

I am attempting to add the results of doubling every other number in an array to a new array. However the code only seems to be pushing the first index that is doubled. I assume the problem is with the .push line but I am not sure. Thanks for any help!
Here is the code I have:
const addTwoDigits = n => {
return n % 10 + Math.floor(n / 10);
}
const validateCred = array => {
let sumNums = []
let i = array.length - 2
while (i > 0) {
let doubleNum = (array[i] * 2)
if (doubleNum > 9) {
let addedNum = addTwoDigits(doubleNum)
sumNums.push(addedNum)
} else {
sumNums.push(doubleNum)
}
i--;
return sumNums;
}
}
const testArray = [4, 2, 1, 6, 5, 7, 5]
console.log(validateCred(testArray));
I was hoping the sumNums array would contain every other digit doubled (starting with '' in the test array and moving left) but it only returns [ 5 ].
You returned the value in the loop. When the compiler comes in loop then first time it returns the value and break the loop.
const addTwoDigits = n => {
return n % 10 + Math.floor(n / 10);
}
const validateCred = array => {
let sumNums = []
let i = array.length - 2
while (i > 0) {
let doubleNum = (array[i] * 2)
if (doubleNum > 9) {
let addedNum = addTwoDigits(doubleNum)
sumNums.push(addedNum)
} else {
sumNums.push(doubleNum)
}
i--;
}
return sumNums;
}
const testArray = [4, 2, 1, 6, 5, 7, 5]
console.log(validateCred(testArray));
Your can try this code.

I need to write a function that loops through an array of numbers, and returns the odd & even numbers in it's array.

I need to write a function that loops through an array of numbers, and returns the odd & even numbers in it's array.
I'm not sure if there's a better way to do this, and I'm stuck. Is there a way to return both statements?
var myNums = [1, 2, 3, 4, 5, 6, 7, 9];
var evens = [];
var odds = [];
function oddsAndEvens(nums) {
for(var i = 0; i < nums.length; i++){
if(nums[i] % 2 === 0){
evens.push(nums[i])
}
else if (!nums[i] % 2 === 0) {
odds.push(nums[i])
}
}
console.log(evens);
console.log(odds);
//I need it to "return" the array,
//not console log
}
console.log(oddsAndEvens(myNums));
A clean function to separate the evens from the odds.
function arrangeNums(array) {
let odd = array.filter(i=>i%2!==0);
let even = array.filter(i=>i%2===0);
return {even:even,odd:odd};
}
console.log(arrangeNums([...Array(100).keys()]));
return arrays instead of console.log should work
var myNums = [1, 2, 3, 4, 5, 6, 7, 9];
var evens = [];
var odds = [];
function oddsAndEvens(nums) {
for(var i = 0; i < nums.length; i++){
if(nums[i] % 2 === 0){
evens.push(nums[i])
}
else if (!nums[i] % 2 === 0) {
odds.push(nums[i])
}
}
// return array of values you want
return [evens, odds]
}
console.log(oddsAndEvens(myNums));
You could use an object for the result and taken an array for the keys of the object to push the value.
function getGrouped(array) {
return array.reduce(function (r, a) {
r[['even', 'odd'][a % 2]].push(a);
return r;
}, { odd: [], even: [] });
}
var myNums = [1, 2, 3, 4, 5, 6, 7, 9];
console.log(getGrouped(myNums));
.as-console-wrapper { max-height: 100% !important; top: 0; }
Off course you can, just return an object containing both evens and odds,
function oddsAndEvens(nums)
{
var evens = [];
var odds = [];
for(var i = 0; i < nums.length; i++){
if(nums[i] % 2 === 0){
evens.push(nums[i])
}
else if (!nums[i] % 2 === 0) {
odds.push(nums[i])
}
}
return {"evens":evens,"odds":odds};
}
var myNums = [1, 2, 3, 4, 5, 6, 7, 9];
result = oddsAndEvens(myNums);
console.log(result.evens);
console.log(result.odds);

Convert simple array into two-dimensional array (matrix)

Imagine I have an array:
A = Array(1, 2, 3, 4, 5, 6, 7, 8, 9);
And I want it to convert into 2-dimensional array (matrix of N x M), for instance like this:
A = Array(Array(1, 2, 3), Array(4, 5, 6), Array(7, 8, 9));
Note, that rows and columns of the matrix is changeable.
Something like this?
function listToMatrix(list, elementsPerSubArray) {
var matrix = [], i, k;
for (i = 0, k = -1; i < list.length; i++) {
if (i % elementsPerSubArray === 0) {
k++;
matrix[k] = [];
}
matrix[k].push(list[i]);
}
return matrix;
}
Usage:
var matrix = listToMatrix([1, 2, 3, 4, 4, 5, 6, 7, 8, 9], 3);
// result: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
You can use the Array.prototype.reduce function to do this in one line.
ECMAScript 6 style:
myArr.reduce((rows, key, index) => (index % 3 == 0 ? rows.push([key])
: rows[rows.length-1].push(key)) && rows, []);
"Normal" JavaScript:
myArr.reduce(function (rows, key, index) {
return (index % 3 == 0 ? rows.push([key])
: rows[rows.length-1].push(key)) && rows;
}, []);
You can change the 3 to whatever you want the number of columns to be, or better yet, put it in a reusable function:
ECMAScript 6 style:
const toMatrix = (arr, width) =>
arr.reduce((rows, key, index) => (index % width == 0 ? rows.push([key])
: rows[rows.length-1].push(key)) && rows, []);
"Normal" JavaScript:
function toMatrix(arr, width) {
return arr.reduce(function (rows, key, index) {
return (index % width == 0 ? rows.push([key])
: rows[rows.length-1].push(key)) && rows;
}, []);
}
This code is generic no need to worry about size and array, works universally
function TwoDimensional(arr, size)
{
var res = [];
for(var i=0;i < arr.length;i = i+size)
res.push(arr.slice(i,i+size));
return res;
}
Defining empty array.
Iterate according to the size so we will get specified chunk.That's why I am incrementing i with size, because size can be 2,3,4,5,6......
Here, first I am slicing from i to (i+size) and then I am pushing it to empty array res.
Return the two-dimensional array.
The cleanest way I could come up with when stumbling across this myself was the following:
const arrayToMatrix = (array, columns) => Array(Math.ceil(array.length / columns)).fill('').reduce((acc, cur, index) => {
return [...acc, [...array].splice(index * columns, columns)]
}, [])
where usage would be something like
const things = [
'item 1', 'item 2',
'item 1', 'item 2',
'item 1', 'item 2'
]
const result = arrayToMatrix(things, 2)
where result ends up being
[
['item 1', 'item 2'],
['item 1', 'item 2'],
['item 1', 'item 2']
]
How about something like:
var matrixify = function(arr, rows, cols) {
var matrix = [];
if (rows * cols === arr.length) {
for(var i = 0; i < arr.length; i+= cols) {
matrix.push(arr.slice(i, cols + i));
}
}
return matrix;
};
var a = [0, 1, 2, 3, 4, 5, 6, 7];
matrixify(a, 2, 4);
http://jsfiddle.net/andrewwhitaker/ERAUs/
Simply use two for loops:
var rowNum = 3;
var colNum = 3;
var k = 0;
var dest = new Array(rowNum);
for (i=0; i<rowNum; ++i) {
var tmp = new Array(colNum);
for (j=0; j<colNum; ++j) {
tmp[j] = src[k];
k++;
}
dest[i] = tmp;
}
function matrixify( source, count )
{
var matrixified = [];
var tmp;
// iterate through the source array
for( var i = 0; i < source.length; i++ )
{
// use modulous to make sure you have the correct length.
if( i % count == 0 )
{
// if tmp exists, push it to the return array
if( tmp && tmp.length ) matrixified.push(tmp);
// reset the temporary array
tmp = [];
}
// add the current source value to the temp array.
tmp.push(source[i])
}
// return the result
return matrixified;
}
If you want to actually replace an array's internal values, I believe you can call the following:
source.splice(0, source.length, matrixify(source,3));
This a simple way to convert an array to a two-dimensional array.
function twoDarray(arr, totalPerArray) {
let i = 0;
let twoDimension = []; // Store the generated two D array
let tempArr = [...arr]; // Avoid modifying original array
while (i < arr.length) {
let subArray = []; // Store 2D subArray
for (var j = 0; j < totalPerArray; j++) {
if (tempArr.length) subArray.push(tempArr.shift());
}
twoDimension[twoDimension.length] = subArray;
i += totalPerArray;
}
return twoDimension;
}
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
twoDarray(arr, 3); // [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ]
function changeDimension(arr, size) {
var arrLen = arr.length;
var newArr = [];
var count=0;
var tempArr = [];
for(var i=0; i<arrLen; i++) {
count++;
tempArr.push(arr[i]);
if (count == size || i == arrLen-1) {
newArr.push(tempArr);
tempArr = [];
count = 0;
}
}
return newArr;
}
changeDimension([0, 1, 2, 3, 4, 5], 4);
function matrixify(array, n, m) {
var result = [];
for (var i = 0; i < n; i++) {
result[i] = array.splice(0, m);
}
return result;
}
a = matrixify(a, 3, 3);
function chunkArrToMultiDimArr(arr, size) {
var newArray = [];
while(arr.length > 0)
{
newArray.push(arr.slice(0, size));
arr = arr.slice(size);
}
return newArray;
}
//example - call function
chunkArrToMultiDimArr(["a", "b", "c", "d"], 2);
you can use push and slice like this
var array = [1,2,3,4,5,6,7,8,9] ;
var newarray = [[],[]] ;
newarray[0].push(array) ;
console.log(newarray[0]) ;
output will be
[[1, 2, 3, 4, 5, 6, 7, 8, 9]]
if you want divide array into 3 array
var array = [1,2,3,4,5,6,7,8,9] ;
var newarray = [[],[]] ;
newarray[0].push(array.slice(0,2)) ;
newarray[1].push(array.slice(3,5)) ;
newarray[2].push(array.slice(6,8)) ;
instead of three lines you can use splice
while(array.length) newarray.push(array.splice(0,3));
const x: any[] = ['abc', 'def', '532', '4ad', 'qwe', 'hf', 'fjgfj'];
// number of columns
const COL = 3;
const matrix = array.reduce((matrix, item, index) => {
if (index % COL === 0) {
matrix.push([]);
}
matrix[matrix.length - 1].push(item);
return matrix;
}, [])
console.log(matrix);
Using the Array grouping proposal (currently stage 3), you can now also do something like the following:
function chunkArray(array, perChunk) {
return Object.values(array.group((_, i) => i / perChunk | 0));
}
See also the MDN documentation for Array.prototype.group().
Simplest way with ES6 using Array.from()
const matrixify = (arr, size) =>
Array.from({ length: Math.ceil(arr.length / size) }, (v, i) =>
arr.slice(i * size, i * size + size));
const list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] ;
console.log(matrixify(list, 3));
Another stab at it,
Creating an empty matrix (Array of row arrays)
Iterating arr and assigning to matching rows
function arrayToMatrix(arr, wantedRows) {
// create a empty matrix (wantedRows Array of Arrays]
// with arr in scope
return new Array(wantedRows).fill(arr)
// replace with the next row from arr
.map(() => arr.splice(0, wantedRows))
}
// Initialize arr
arr = new Array(16).fill(0).map((val, i) => i)
// call!!
console.log(arrayToMatrix(arr, 4));
// Trying to make it nice
const arrToMat = (arr, wantedRows) => new Array(wantedRows).fill(arr)
.map(() => arr.splice(0, wantedRows))
(like in: this one)
(and: this one from other thread)
MatArray Class?
Extending an Array to add to a prototype, seems useful, it does need some features to complement the Array methods, maybe there is a case for a kind of MatArray Class? also for multidimensional mats and flattening them, maybe, maybe not..
1D Array convert 2D array via rows number:
function twoDimensional(array, row) {
let newArray = [];
let arraySize = Math.floor(array.length / row);
let extraArraySize = array.length % row;
while (array.length) {
if (!!extraArraySize) {
newArray.push(array.splice(0, arraySize + 1));
extraArraySize--;
} else {
newArray.push(array.splice(0, arraySize));
}
}
return newArray;
}
function twoDimensional(array, row) {
let newArray = [];
let arraySize = Math.floor(array.length / row);
let extraArraySize = array.length % row;
while (array.length) {
if (!!extraArraySize) {
newArray.push(array.splice(0, arraySize + 1));
extraArraySize--;
} else {
newArray.push(array.splice(0, arraySize));
}
}
return newArray;
}
console.log(twoDimensional([1,2,3,4,5,6,7,8,9,10,11,12,13,14], 3))
Short answer use:
const gridArray=(a,b)=>{const d=[];return a.forEach((e,f)=>{const
h=Math.floor(f/b);d[h]=d[h]||[],d[h][f%b]=a[f]}),d};
Where:
a: is the array
b: is the number of columns
An awesome repository here .
api : masfufa.js
sample : masfufa.html
According to that sample , the following snippet resolve the issue :
jsdk.getAPI('my');
var A=[1, 2, 3, 4, 5, 6, 7, 8, 9];
var MX=myAPI.getInstance('masfufa',{data:A,dim:'3x3'});
then :
MX.get[0][0] // -> 1 (first)
MX.get[2][2] // ->9 (last)

Categories

Resources