Convert simple array into two-dimensional array (matrix) - javascript

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)

Related

Create Possible Combination in javascript/typescript/nodejs

let input = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
and i want output should be:
output = {
first: [[1,2], [3,4], [5,6], [7,8], [9,10]],
second: [[1,3], [2,4], [5,7], [6,9], [8,10]],
third: [[1,4], [2,3], [5,8], [7,9], [6,10]],
fourth: [[1,5], [2,6], [3,7], [8,9], [4,10]],
fifth: [[1,6], [2,8], [3,5], [4,9], [7,10]],
sixth: [[1,7], [2,9], [3,6], [4,8], [5,10]],
seventh: [[1,8], [2,7], [4,6], [5,9], [3,10]],
eighth: [[1,9], [3,8], [4,5], [6,7], [2,10]],
ninth: [[1,10], [2,5], [3,9], [4,7], [6,8]],
}
I need to write a code in javascript / typescript / nodejs by which i can put number ranges and will get a combinations of given numbers**( n-1 ), i want a code to be written which can return us **all possible combination and the combination will never conflict with other combinations.
Thanks in advance.
You could take a brute force approach with a recursive function for collected pairs and a list of available pairs.
If a new pair is possible to get, take this pair and call the function again.
function getAllPairs(array) {
var pairs = [];
for (let i = 0; i < array.length - 1; i++) {
for (let j = i + 1; j < array.length; j++) {
pairs.push([array[i], array[j]]);
}
}
return pairs;
}
function fill(pairs, result = []) {
function check(array) {
return array.every((s => a => a.every(v => !s.has(v) && s.add(v)))(new Set));
}
if (!pairs.length) return result;
var left = result.slice(Math.floor(result.length / half) * half);
for (let i = 0; i < pairs.length; i++) {
if (!check([...left, pairs[i]])) continue;
var newResult = fill([...pairs.slice(0, i), ...pairs.slice(i + 1)], [...result, pairs[i]]);
if (newResult) return newResult; // i miss something like returnIf
}
}
var data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
half = data.length / 2,
temp = fill(getAllPairs(data)),
result = [],
i = 0;
while (i < temp.length) result.push(temp.slice(i, i += half));
result.forEach(a => console.log(...a.map(a => a.map(v => v.toString().padStart(2, ' ')).join('|'))));
.as-console-wrapper { max-height: 100% !important; top: 0; }

Recursion is skipping values

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);

Sorting an array by chunks of 3

Assume that you have an array and want to divide it by chunks of 3. If the array is..
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];
...the new array would be
let newArr = [1, 4, 7, 10, 13, 2, 5, 8, 11, 3, 6, 9, 12]
// In other words:
1 2 3
4 5 6
7 8 9
10 11 12
13
The chunking part should be this code (if sorted like newArr):
let chunkedArr = _.chunk(_.toArray(newArr), 3);
...however I couldn't figure out how to sort the arr to newArr to be able to chunk in the right order. What is the proper way of handling such case?
Please note that the integers are just pseudo and I will use proper objects of array.
One option is to use ES6 reduce to group the array into a multidimensional array. Use concat to flatten the multidimensional array.
[].concat(...) - basically flattens the multidimensional array. Starting with an empty array [], you concat each secondary array. Use the spread operator (...) to reiterate each secondary array and concat each.
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];
let groups = 3;
let newArr = [].concat(...arr.reduce((c, v, i) => {
let k = i % groups;
c[k] = c[k] || [];
c[k].push(v);
return c;
}, []));
console.log(newArr);
Please try the following (jsfiddle):
//This version works for variable chunk sizes as well.
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];
alert(chunks(arr, 3)); //You can update chunk size here
function chunks(arr, chunkSize) {
var result = [];
var index = 0;
for (var i = 0; i < chunkSize; i++) {
for (var j = 0; j < arr.length / chunkSize; j++) {
if (arr[i + (chunkSize * j)] != null)
result[index++] = arr[i + (chunkSize * j)];
}
}
return result;
}
//This version only works for chunks of size 3.
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];
let subArr1 = [];
let subArr2 = [];
let subArr3 = [];
var result = [];
var i = 0, j = 0, k = 0;
for (var index = 0; index < arr.length; index++) {
if (index % 3 == 0) {
subArr1[i++] = arr[index];
}
if (index % 3 == 1) {
subArr2[j++] = arr[index];
}
if (index % 3 == 2) {
subArr3[k++] = arr[index];
}
}
result.push(subArr1, subArr2, subArr3);
alert(result);
Please check this it may help you. I also take a reference from here. Please check and let us know. any thing else you need.
Thanks
Here is the sample code.
var i,j,resArr,chunkSize = 10;
for (i=0,j=array.length; i<j; i+=chunk) {
resArr = array.slice(i,i+chunk);
}
const original = [1,2,3,4,5,6,7,8,9,10,11,12,13]
const chunks = 3
function getChunckedArr(arr, n) {
let sub = new Array(n);
let result = [];
for (let i=0; i<sub.length; i++)
sub[i] = []
arr.forEach(function (val, index){
let o = (index % n);
sub[o][sub[o].length] = val;
});
for (let i=0; i<sub.length; i++)
result.push.apply(result, sub[i]);
return result;
}
const chunked = getChunckedArr(original, chunks);

Group identical values in array

I have an array that has some values inside, and I wish to return another array that has the value grouped in to their own arrays.
So the result I am trying to achieve is something like this:
var arr = [1,1,2,2,2,3,3,4,4,4,4,5,6]
var groupedArr =[[1,1],[2,2,2],[3,3],[4,4,4,4],[5],[6]]
This proposal works with Array#reduce for sorted arrays.
var arr = [1, 1, 2, 2, 2, 3, 3, 4, 4, 4, 4, 5, 6],
groupedArr = arr.reduce(function (r, a, i) {
if (!i || a !== r[r.length - 1][0]) {
return r.concat([[a]]);
}
r[r.length - 1].push(a);
return r;
}, []);
document.write('<pre>' + JSON.stringify(groupedArr, 0, 4) + '</pre>');
Here you go. By the way, this works with unsorted array as well.
var arr = [1, 1, 2, 2, 2, 3, 3, 4, 4, 4, 4, 5, 6]
var grpdArr = [];
while(arr.length > 0){
var item = arr[0];
grpdArr.push(arr.filter(function(val) {
return val === item;
}));
arr = arr.filter(function(val){return val!==item});
}
//console.log(arr, grpdArr);
Well this should do. Pretty straight forward..,
You get the elements and then remove them.
With forEach and temporary array
var arr = [1, 1, 2, 2, 2, 3, 3, 4, 4, 4, 4, 5, 6];
var temp = [];
var res = [];
arr.forEach(function(e) {
if (temp.slice(-1) == e) temp.push(e);
else {
temp = [e];
res.push(temp);
}
});
document.write(JSON.stringify(res));
This may not be the most optimal version but should do. This also works for unsorted arrays.
function abc(arr) {
var newObj = new Object();
for (var i in arr) {
if (typeof newObj[arr[i]] == 'undefined') {
newObj[arr[i]] = new Array();
}
newObj[arr[i]].push(arr[i]);
}
var groupedArr = new Array();
for (i in newObj) {
groupedArr.push(newObj[i]);
}
return groupedArr;
}
console.log(abc([1, 1, 2, 2, 3, 3, 3, 4, 1]));
This is the most straightforward in my mind:
var arr = [1,1,2,2,2,3,3,4,4,4,4,5,6];
var grouped = {};
var groupedArr = [];
//accumulate the values in an object, each key is an array
for (var i = 0; i < arr.length; i++) {
if (!grouped[arr[i]]) grouped[arr[i]] = [];
grouped[arr[i]].push(arr[i]);
}
//loop through all the keys in the object and push the arrays to the master array
var keys = Object.keys(grouped);
for (var i = 0; i < keys.length; i++) {
groupedArr.push(grouped[keys[i]]);
}
console.log(groupedArr);
I think you could use the code below:
var arr = [1,1,2,2,2,3,3,4,4,4,4,5,6]
var groupedArray = [];
var temp = arr.sort();
var tempArray = [arr[0]];
for(var i = 0; i < temp.length - 1; ++i){
if(temp[i] == temp[i + 1]){
tempArray.push(temp[i + 1]);
}else{
groupedArray.push(tempArray);
tempArray = [temp[i + 1]];
}
}
groupedArray.push(tempArray);
Now the groupedArray will contain the Result

split an array into two arrays based on odd/even position

I have an array Arr1 = [1,1,2,2,3,8,4,6].
How can I split it into two arrays based on the odd/even-ness of element positions?
subArr1 = [1,2,3,4]
subArr2 = [1,2,8,6]
odd = arr.filter (v) -> v % 2
even = arr.filter (v) -> !(v % 2)
Or in more idiomatic CoffeeScript:
odd = (v for v in arr by 2)
even = (v for v in arr[1..] by 2)
You could try:
var Arr1 = [1,1,2,2,3,8,4,6],
Arr2 = [],
Arr3 = [];
for (var i=0;i<Arr1.length;i++){
if ((i+2)%2==0) {
Arr3.push(Arr1[i]);
}
else {
Arr2.push(Arr1[i]);
}
}
console.log(Arr2);
JS Fiddle demo.
It would be easier using nested arrays:
result = [ [], [] ]
for (var i = 0; i < yourArray.length; i++)
result[i & 1].push(yourArray[i])
if you're targeting modern browsers, you can replace the loop with forEach:
yourArray.forEach(function(val, i) {
result[i & 1].push(val)
})
A functional approach using underscore:
xs = [1, 1, 2, 2, 3, 8, 4, 6]
partition = _(xs).groupBy((x, idx) -> idx % 2 == 0)
[xs1, xs2] = [partition[true], partition[false]]
[edit] Now there is _.partition:
[xs1, xs2] = _(xs).partition((x, idx) -> idx % 2 == 0)
var Arr1 = [1, 1, 2, 2, 3, 8, 4, 6]
var evenArr=[];
var oddArr = []
var i;
for (i = 0; i <= Arr1.length; i = i + 2) {
if (Arr1[i] !== undefined) {
evenArr.push(Arr1[i]);
oddArr.push(Arr1[i + 1]);
}
}
console.log(evenArr, oddArr)
I guess you can make 2 for loops that increment by 2 and in the first loop start with 0 and in the second loop start with 1
A method without modulo operator:
var subArr1 = [];
var subArr2 = [];
var subArrayIndex = 0;
var i;
for (i = 1; i < Arr1.length; i = i+2){
//for even index
subArr1[subArrayIndex] = Arr1[i];
//for odd index
subArr2[subArrayIndex] = Arr1[i-1];
subArrayIndex++;
}
//For the last remaining number if there was an odd length:
if((i-1) < Arr1.length){
subArr2[subArrayIndex] = Arr1[i-1];
}
Just for fun, in two lines, given that it's been tagged coffeescript :
Arr1 = [1,1,2,2,3,8,4,6]
[even, odd] = [a, b] = [[], []]
([b,a]=[a,b])[0].push v for v in Arr1
console.log even, odd
# [ 1, 2, 3, 4 ] [ 1, 2, 8, 6 ]
As a one-liner improvement to tokland's solution using underscore chaining function:
xs = [1, 1, 2, 2, 3, 8, 4, 6]
_(xs).chain().groupBy((x, i) -> i % 2 == 0).values().value()
filters is a non-static & non-built-in Array method , which accepts literal object of filters functions & returns a literal object of arrays where the input & the output are mapped by object keys.
Array.prototype.filters = function (filters) {
let results = {};
Object.keys(filters).forEach((key)=>{
results[key] = this.filter(filters[key])
});
return results;
}
//---- then :
console.log(
[12,2,11,7,92,14,5,5,3,0].filters({
odd: (e) => (e%2),
even: (e) => !(e%2)
})
)

Categories

Resources