Related
How to completely remove repeated numbers from an array?
For example, if:
const array = [1, 1, 2, 3, 1, 2, 5]
The output should be:
[3, 5]
You could take an object for keeping track of seen items, by taking an array with the value or set the arrays value to zero.
Finally flat the result set to remove empty arrays.
const
array = [1, 1, 2, 3, 1, 2, 5],
result = array
.reduce((o => (r, v) => {
if (v in o) o[v].length = 0;
else r.push(o[v] = [v]);
return r;
})({}), [])
.flat();
console.log(result);
Roko and Ke1vans had answered in functional approaches. Both of them are correct. However, I'd show an answer in imperative approach, which may seems easier for new comer.
Similar to their flow. First, we count the occurrence of each number. Then we select the numbers that has occurred once (hence being non-repeated) into the output array.
let array = [1,1,2,3,1,2,5]
let counts = {}
let output = []
// loop each elements in the array as `item`
for(let item of array) {
// If the item is not set in the counts, `counts[item]` will be `undefined`.
// Using `|| 0` means use zero as fallback value if the items is unseen.
let count = counts[item] || 0
counts[item] = count + 1
}
// loop each keys in the object (key-value pairs) as `item`
for(let item in counts) {
let count = counts[item]
if(count == 1) {
// `+item` converts the key from string into number
output.push(+item)
}
}
console.log(output) // will print out `[ 3, 5 ]`
You can iterate and create a map of values. later iterate and filter.
const data = [1, 1, 2, 3, 1, 2, 5];
const findUniques = (data = []) => {
const map = data.reduce((m, num) => {
m[num] = (m[num] || 0) + 1;
return m;
}, {});
return data.filter((num) => map[num] === 1);
};
console.log(findUniques(data));
You can also do the same using 2 set, or 2 array.
const data = [1, 1, 2, 3, 1, 2, 5];
const findUniques2 = (data = []) => {
let unique = new Set();
let seen = new Set();
for (let num of data) {
if (seen.has(num)) unique.delete(num);
else unique.add(num);
seen.add(num);
}
return Array.from(unique);
};
console.log(findUniques2(data));
Use an Object where the key is the number, and the value is the number of occurrences. Than reduce it back to the desired array of values:
const arr = [1,1,2,3,1,2,5];
const res = Object.entries(arr.reduce((ob, v) => {
if (!(v in ob)) ob[v] = 0;
ob[v] += 1; // Count occurrences
return ob;
}, {})).reduce((arr, [k, v]) => { // Reduce back to Array
if (v === 1) arr.push(+k); // Only keys with 1 occurrence
return arr;
}, []);
console.log(res); // [3, 5]
You can use Array.filter() (Array filter article) for this for Example :
const a = [ 1 , 1 , 2 , 3 , 2 , 4 , 5 , 7];
function filter(value , index , array){
// looping through all the objects in the array
for(let i=0; i<array.length; i++) {
if(i != index && array[i] == value) return false; // return 'false' if the value has a duplicate other than itself
}
// return 'TRUE' if value hasn't been duplicated
return true;
}
const b = a.filter(filter); // [3, 4, 5, 7]
And the short version if this function's going to be used only once:
const a = [ 1 , 1 , 2 , 3 , 2 , 4 , 5 , 7];
const b = a.filter((value , index , array) => {
for(let i=0; i<array.length; i++) if(i != index && array[i] == value) return false;
return true;
});
// [3, 4, 5, 7]
You could find duplicates and then operate a difference.
let a = [1,1,2,3,1,2,5];
const findDuplicates = (nums) => {
nums.sort(); // alters original array
let ans = []
for(let i = 0; i< nums.length; i++){
if(nums[i] === nums[i+1]){
if(ans[ans.length -1] !== nums[i]){
ans.push(nums[i])
}
}
}
return ans;
}
duplicates = new Set(findDuplicates(a))
let difference = new Set([...a].filter(x => !duplicates.has(x)))
console.log(Array.from(difference))
output : [ 3, 5 ]
Note : I grab the findDuplicates function from this link
const data = [1, 1, 2, 3, 1, 2, 5];
const s = new Set();
const res = data.filter((a, i) => {
if (data.lastIndexOf(a) > i || s.has(a)) {
s.add(a);
return false;
}
return true;
});
console.log(res); //=> [3, 5]
I have an array a = [1,1,1,2,2,3,3,3,4,4,4,6,6,6,7,7]
I want to fetch all the duplicate pair in this array list.
Since there are pairs of 2 and 7 the output should be -
Output: [2, 7]
I tried writing my own logic but I am very weak in that area. Can somebody help?
function getDuplicateArrayElements(arr){
let sorted_arr = arr.slice().sort();
let results = [];
for (let i = 0; i < sorted_arr.length; i++) {
let matchingElementCount = 1;
for (let j = i + 1; j < sorted_arr.length - i; j++) {
if (sorted_arr[j] === sorted_arr[i]) {
++matchingElementCount;
} else {
if(matchingElementCount % 2 === 0) {
results.push(sorted_arr[i]);
}
i = j - 1;
break;
}
}
}
return results; } var a = [1,1,1,2,2,3,3,3,4,6,6,6,7,7]; var duplicateValues= getDuplicateArrayElements(a);
You can achieve your result by using reduce and forEach.
const arr = [1,1,1,1,2,2,3,3,3,4,4,4,6,6,6,7,7];
// Generate a hashmap from the given array for counting the frequency.
const hashMap = arr.reduce((a, c) => {
a[c] = (a[c] || 0) + 1;
return a;
}, {});
const pair = [];
// If the frequency is divided by 2 then push the key of the hashMap into pair array.
Object.entries(hashMap).forEach(([k, v]) => {
if (v % 2 === 0) {
[...Array(Math.floor(v / 2))].forEach(_ => pair.push(k));
}
})
console.log(pair);
You can grab the frequency of each number, and then filter out any which have an odd frequency. You can then .flatMap() the frequencies to an array containing your number for each pair you found like so:
const a = [1,1,1,2,2,3,3,3,4,4,4,6,6,6,7,7];
const freq = a.reduce((m, n) => m.set(n, (m.get(n) || 0) + 1), new Map);
const res = [...freq].filter(([n, count]) => count % 2 == 0).flatMap(([n, c]) => Array(c/2).fill(n));
console.log(res);
This way, if you have four 1s (ie: two pairs of 1s), the filter will pick up on that, allowing you to flat-map the [1, 4] array to an array of [1, 1], which is merged into the larger resulting array.
You could create a helper map and keep the counts of each number as the values and the numbers itself as the keys. After iterating through the array, you only need to find the ones with a count divisible by 2:
var a = [1, 1, 1, 2, 2, 3, 3, 3, 4, 6, 6, 6, 7, 7]
function findDuplicates(arr) {
const map = {};
for (const curr of arr) {
if (!map[curr]) {
map[curr] = 0;
}
map[curr]++;
}
const res = [];
for (const key in map) {
if (map.hasOwnProperty(key) && map[key] % 2 === 0) {
res.push(Number.parseInt(key));
}
}
return res;
}
console.log(findDuplicates(a));
You can first count the occurrence of each numbers and if it is greater than 0 and divisible by 2 then add these to final result else don't
function getDuplicateArrayElements(arr) {
let map = {}
let results = [];
for (let num of arr) {
map[num] = map[num] || 0
map[num]++
}
return Object.keys(map)
.filter(v => map[v] && map[v] % 2 === 0)
.map(v => new Array(map[v]/2).fill(+v))
.flat()
.sort()
}
var a = [1, 1, 1, 2, 2, 3, 3, 3, 4, 6, 6, 6, 7, 7,8,8,8,8];
var duplicateValues = getDuplicateArrayElements(a);
console.log(duplicateValues)
const a = {};
[1,1,1,2,2,3,3,3,4,6,6,6,7,7].forEach(v => {a[v] = a[v] ? a[v] + 1 : 1});
const l = [];
Object.keys(a).forEach(k => !(a[k] % 2) && l.push(k));
Here you go:
function getDuplicateArrayElements(arr){
var dupilcates=arr.filter(x => arr.filter(y=>y==x).length==2);
var found=[];
for(var i=0;i<dupilcates.length;i=i+2)
found.push(dupilcates[i]);
return found;
}
This will give you the desired pairs. with [1, 1, 1, 1, 2, 2, 3, 3, 3, 4, 6, 6, 6, 6, 7, 7] input it will return [1,1,2,6,6,7]:
function getDuplicateArrayElements(arr){
let sorted_arr = arr.slice().sort();
let results = [];
let i = 0;
while (i < sorted_arr.length) {
let counter = 1;
let j = i;
while (sorted_arr[j] === sorted_arr[j+1]) {
counter++;
j++;
}
if (counter%2 == 0) {
results.push(...Array(counter/2).fill(sorted_arr[i]))
}
i += counter;
}
return results;
}
var a = [1, 1, 1, 1, 2, 2, 3, 3, 3, 4, 6, 6, 6, 6, 7, 7];
console.log(getDuplicateArrayElements(a));
Another rather concise solution:
a = [1,1,1,2,2,3,3,3,4,4,4,6,6,6,7,7];
uniques = new Set(a); //filter out duplicates
res = [];
uniques.forEach((key)=>{
if(a.filter(elem => elem === key).length === 2){res.push(key)};
//filter out only the elements which match the key being tested
//if there are 2, push to result
})
Edit: even more concise, but perhaps less efficient:
a = [1,1,1,2,2,3,3,3,4,4,4,6,6,6,7,7];
res = Array.from(new Set(a.filter(elem => a.filter(el => el === elem).length === 2)));
Javascript has awesome JSON object, in my opinion, you can use json as a dictionary;
{ key: _value }.
Loop throw array one times, no sort, no slice
key is array's element value, _value is frequency
var frequencies = {};
for (let i = 0; i < a.length; a++) {
if (result[a[i]] == 'over') continue;
if (result[a[i]] == undefined) { // First times
result[a[i]] = 1
} else if (result[a[i]] == 1) { // Second times
result[a[i]] = 2
} else { // Ignore if > 2
result[a[i]] = 'over'
}
}
// result: {1: "over", 2: 2, 3: "over", 4: "over", 6: "over", 7: 2}
so now pick keys have value equal 2
function getDuplicateArrayElements(numbers: number[]): number[] {
const occurences = new Map<number, number>();
for (let number of numbers) {
if (occurences.has(number)) {
const current = occurences.get(number)!;
occurences.set(number, current + 1);
} else
occurences.set(number, 1)
}
return (
Array
.from(occurences.entries())
.reduce<number[]>(
(accumulator, [key, value]) => {
if (value === 2) {
return accumulator.concat(key)
}
return accumulator
},
[]
)
)
}
const a = [1, 1, 1, 2, 2, 3, 3, 3, 4, 4, 4, 6, 6, 6, 7, 7];
getDuplicateArrayElements(a); // [2, 7]
I've tried a few approaches to this but I can't seem to come up with a viable solution...
In short, I want to create a function to transform a 1D array of any length into a new 2D array of a specific length. Each value from the 1D array should be sequentially placed into each child-array up to the specified length, then start back at the first child-array.
Input / Desired Output Below:
function groupArray(arr, numberOfGroups) {
...
};
// Input Data
const items = [1, 2, 3, 4, 5, 6, 7];
const size = 3;
console.log(groupArray(items, size));
// Expected Output
// [[1, 4, 7], [2, 5], [3, 6]]
You could take the reminder operator % with index and wanted size of the array for getting the right target array.
const
groupArray = (array, size) => array.reduce((result, value, index) => {
const target = index % size;
if (!result[target]) result[target] = [];
result[target].push(value);
return result;
}, []);
console.log(groupArray([1, 2, 3, 4, 5, 6, 7], 3));
.as-console-wrapper { max-height: 100% !important; top: 0; }
Using nested for
function groupArray(arr, numberOfGroups) {
var result = []
for (var i = 0; i < numberOfGroups; i++) {
var subarr = []
for (var j = i; j < arr.length; j += numberOfGroups) {
subarr.push(arr[j])
}
result.push(subarr)
}
return result
};
// Input Data
const items = [1, 2, 3, 4, 5, 6, 7];
const size = 3;
console.log(groupArray(items, size));
Also something like this would do it,
you'd not need to mutate any input
const chunkify = (step, list) => list.reduce(
([chunk, rest], item, i) => {
const pick = i % step === 0;
return [
chunk.concat(pick ? item : []),
rest.concat(pick ? [] : item),
];
},
[[], []],
);
const group = (step, list, result = []) => {
if (!list.length) { return result; }
const [chunk, rest] = chunkify(step, list);
return group(step - 1, rest, [...result, chunk]);
};
const data = [1, 2, 3, 4, 5, 6, 7];
const step = 3;
console.log(
group(step, data),
);
Have method next, each call will return next index and when limit reaches numberOfGroups reset the index 0. (in this case, it will be like 0, 1, 2, 0, 1, 2....)
With this method, can easily push to corresponding output sub array.
const groupArray = (arr, numberOfGroups) => {
const output = Array.from({ length: numberOfGroups }, () => []);
const next = index => index % numberOfGroups;
arr.forEach((num, i) => output[next(i)].push(num));
return output;
};
// Input Data
const items = [1, 2, 3, 4, 5, 6, 7];
const size = 3;
console.log(groupArray(items, size));
I'm given an array of numbers. I have created an object named counts, whose keys are the numbers and values the amount of times those numbers appear in the array. Can't work out how to use reduce to delete the even counts of the numbers.
A = [ 20, 1, -1, 2, -2, 3, 3, 5, 5, 1, 2, 4, 20, 4, -1, -2, 5 ]
n = 5
function findOdd(A) {
let counts = {};
for (let i = 0; i < A.length; i++) {
let num = A[i];
counts[num] = counts[num] ? counts[num] + 1 : 1;
}
//counts -> { '1': 2, '2': 2, '3': 2, '4': 2, '5': 3, '20': 2, '-1': 2, '-2': 2 }
const answer = Object.keys(counts).reduce((object, key) => {
if (key % 2 !== 0) {
object[key] = counts[key];
}
return object;
}, {})
return answer;
Must return the key of the odd count.
SOLUTION:
function findOdd(A) {
const counts = {};
for (let i = 0; i < A.length; i++) {
let num = A[i];
counts[num] = counts[num] ? counts[num] + 1 : 1;
}
Object.keys(counts).forEach(key => {
if(counts[key] % 2 === 0) {
delete counts[key];
}
});
return Number(Object.keys(counts));
}
You can make use of Object.entries to obtain entires, then filter entries whose values are odd, and then reconstruct new Object from those entries using Object.fromEntries:
const countObject = { '1': 2, '2': 2, '3': 2, '4': 2, '5': 3, '20': 2, '-1': 2, '-2': 2 };
const oddEntries = Object.entries(countObject).filter(([key, value]) => value % 2 !== 0);
const oddCountObject = Object.fromEntries(oddEntries)
console.log(oddCountObject)
function findOdd(arr) {
const counts = {}; // `const` declared objects/arrays are not immutable
for(let i = 0; i < arr.length; i++) {
counts[arr[i]] = counts[arr[i]] || 0;
counts[arr[i]]++;
}
Object.keys(counts).forEach(key => {
if(counts[key] % 2 === 0) {
delete counts[key];
}
});
return counts;
}
const array = [1, 2, 3, 4, 5, 6, 1, 1, 4, 5, 4, 9];
// 1:3, 2:1, 3:1, 4:3, 6:1, 9:1
// Does not show a `5` key due to there being an even number of fives in `array`
console.log(findOdd(array));
Yes, I know delete is inefficient, but that shouldn't matter, unless it is a requirement for being quick. I believe you can just set counts[key] = undefined or counts[key] = null, you can see the benchmarks here
I know there are already great answers but as the question said "using reduce" I thought it'd be fun to try doing this using only reduce:
const findOdd = arr => arr.reduce((acc, d, i, list) => {
if (!acc[d]) {
acc[d] = 0;
}
acc[d]++;
if (i === list.length - 1) {
return Object.keys(acc)
.reduce((subAcc, key) => ({
...subAcc,
...(acc[key] % 2 === 0 ? {} : {
[key]: acc[key]
})
}), {})
}
return acc;
}, {})
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)