This question already has answers here:
Convert simple array into two-dimensional array (matrix)
(19 answers)
Closed 8 years ago.
I am working on a program where I have to read the values from a textfile into an 1D array.I have been succesfull in getting the numbers in that 1D array.
m1=[1,2,3,4,5,6,7,8,9]
but I want the array to be
m1=[[1,2,3],[4,5,6],[7,8,9]]
You can use this code :
const arr = [1,2,3,4,5,6,7,8,9];
const newArr = [];
while(arr.length) newArr.push(arr.splice(0,3));
console.log(newArr);
http://jsfiddle.net/JbL3p/
Array.prototype.reshape = function(rows, cols) {
var copy = this.slice(0); // Copy all elements.
this.length = 0; // Clear out existing array.
for (var r = 0; r < rows; r++) {
var row = [];
for (var c = 0; c < cols; c++) {
var i = r * cols + c;
if (i < copy.length) {
row.push(copy[i]);
}
}
this.push(row);
}
};
m1 = [1, 2, 3, 4, 5, 6, 7, 8, 9];
m1.reshape(3, 3); // Reshape array in-place.
console.log(m1);
.as-console-wrapper { top:0; max-height:100% !important; }
Output:
[
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
JSFiddle DEMO
I suppose you could do something like this... Just iterate over the array in chunks.
m1=[1,2,3,4,5,6,7,8,9];
// array = input array
// part = size of the chunk
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, 3)); // [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ]
Obviously there is no error checking, but you can easily add that.
DEMO
There are so many ways to do the same thing:
var m = [1, 2, 3, 4, 5, 6, 7, 8, 9];
var n = [];
var i = 0;
for (l = m.length + 1; (i + 3) < l; i += 3) {
n.push(m.slice(i, i + 3));
}
// n will be the new array with the subarrays
The above is just one.
Related
This question already has answers here:
Split array into chunks
(73 answers)
Closed 8 months ago.
This post was edited and submitted for review 8 months ago and failed to reopen the post:
Original close reason(s) were not resolved
I would like to create a two-dimensional array based on targetItems with the number of numbers in splitNumber and output it as follows.
const targetItems = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const splitNumber = 2;
We are looking for the following results.
[[1, 2, 3, 4, 5], [6, 7, 8, 9]];
Is there a good way?
I was thinking of using Math.round, etc. to carry it out if it can't be done evenly.
If the number of targetItems is 5 and the splitNumber is 2
[[1,2,3], [4,5]]
If the number of targetItems is 17 and the splitNumber is 2
[[1,2,3,4,5,6,7,8,9], [10,11,12,13,14,15,16,17]]
If the number of targetItems is 5 and the splitNumber is 3
[[1,2], [3,4], [5]]
Basically, we use the arary.slice(start,end) method splitNumber of times, having the bigger parts first. The results depend indeed on how you define the problem in the first place. So this code might need changes.
const targetItems = [1, 2, 3, 4, 5, 6, 7, 8, 9];
function split(targetItems, splitNumber) {
const half = Math.ceil(targetItems.length / splitNumber);
var parts = [];
for (var i = 0; i < splitNumber; i++) {
parts.push(targetItems.slice(i * half, i * half + half))
}
return parts;
}
for (var i = 1; i <= targetItems.length; i++) {
console.log("split to " + i + " parts", JSON.stringify(split(targetItems, i)))
}
.as-console-wrapper {
max-height: 100% !important;
}
I used this code in my previous project:
var arr = [1,2,3,4,5,6,7,8,9,0]
const arr1l = Math.floor(arr.length/2)
const arr2l = arr.length-arr1l
const arr1 = arr.slice(0,arr1l)
const arr2 = arr.slice(arr1l,arr.length)
var new_arr=[arr1,arr2]
document.querySelector(".h1").innerHTML=arr1
document.querySelector(".h2").innerHTML=arr2
<p class="h1"></p>
<p class="h2"></p>
I used in this way.
const arr = [1,2,3,4,5,6,7,8,9,1,1,2];
function turnIntoTwoDimension(arr) {
let twoDimension = []
twoDimension.push(arr.slice(0,arr.length/2))
twoDimension.push(arr.slice(arr.length/2))
return twoDimension
}
console.log(turnIntoTwoDimension(arr));
const targetItems = [1, 2, 3, 4, 5, 6, 7, 8, 9];
function split(targetItems, splitNumber) {
const half = Math.ceil(targetItems.length / splitNumber);
var parts = [];
for (var i = 0; i < splitNumber; i++) {
parts.push(targetItems.slice(i * half, i * half + half))
}
return parts;
}
for (var i = 1; i <= targetItems.length; i++) {
console.log("split to " + i + " parts", JSON.stringify(split(targetItems, i)))
}
.as-console-wrapper {
max-height: 100% !important;
}
I have an array which represents the points of a graph with different values like the following one:
var array = [5, 3, 4, 1, 2];
I would like to loop through it and create a new array where the new values are:
An average between the value preceding it and the one coming after it.
Placed among the existing ones.
This means that array[0] will remain at the same position, while the other values will be pushed of one position. The new array should look like this:
var newArray = [5, 4, 3, 3.5, 4, 2.5, 1, 1.5, 2];
Do you have an idea on how to achieve this? Thanks in advance to your replies!
var array = [5, 3, 4, 1, 2];
var newArr = [array[0]]; // start the array with the first from the original
array.reduce((a, b) => {
newArr.push((a + b) / 2, b);
return b;
});
console.log(newArr);
var array = [5, 3, 4, 1, 2];
var newArray = [];
newArray.push(array[0]);
for(var i=0; i < array.length-1; i++)
{
var first = array[i];
var second = array[i+1];
var avg = (first+second)/2;
newArray.push(avg);
newArray.push(second);
}
https://jsfiddle.net/5utkvge8/
You are going to want to loop through your original array, pushing each number to the new one, and if you are not on the final element, get the average of array[i] and array[i+1]
var array = [5, 3, 4, 1, 2];
var newArray = [];
for (var i = 0; i < array.length; i++)
{
newArray.push(array[i])
if (!isNaN(array[i+1]))
{
newArray.push((array[i] + array[i+1]) / 2)
}
}
or in a functional, no-side effects, way:
var array = [5, 3, 4, 1, 2];
var newArray = array.reduce((result, value, index, array) => result.concat(index > 0 && index < array.length ? [(array[index-1] + value)/2, value] : value), [])
In case you can modify the original array:
var array = [5, 3, 4, 1, 2],
len = array.length * 2 - 2;
for (var i = 1; i < len; i = i + 2) {
array.splice(i, null, (array[i-1] + array[i]) / 2);
}
console.log(array);
let createdArr = []
[5, 3, 4, 1, 2].forEach( (item,index,arr) => {
createdArr.push(item)
if( index !== 0 && index + 1 !== arr.length ){
createdArr.push( (item + arr[ index + 1]) / 2 )
}
} )
This question already has answers here:
How to get the difference between two arrays in JavaScript?
(84 answers)
Closed 6 years ago.
Say I have the following two arrays:
var arrOne = [1, 4, 7];
var arrTwo = [1, 2, 3, 4, 5];
var arrThree = [];
I'd like to itterate over arrTwo and if it contains an element that is also in arrOne, remove it from arrTwo, and insert it in arrThree. So looking at the above arrays the state of the arrays afterwards should look like this:
var arrOne = [1, 4, 7];
var arrTwo = [2, 3, 5];
var arrThree = [1, 4];
Could anyone point me in the right direction and the best way to go about this? If code is provided, a step-by-step explanation would really be appreciated so that I can understand what's going on.
A simple for loop, matching with indexOf and splicing matches.
var arrOne = [1, 4, 7];
var arrTwo = [1, 2, 3, 4, 5];
var arrThree = [];
for (var i = 0; i < arrTwo.length; i++) {
if (arrOne.indexOf(arrTwo[i]) >= 0) {
arrThree.push(arrTwo[i]);
arrTwo.splice(i, 1);
i--;
}
}
console.log(arrOne, arrTwo, arrThree)
Array.IndexOf
Array.splice
Look into the Underscore library. All the elements in arrOne that are also in arrTwo is called _.intersection().
Use simple while loop with Array#splice and Array#unshift methods.
var arrOne = [1, 4, 7];
var arrTwo = [1, 2, 3, 4, 5];
var arrThree = [];
// get length of array
var l = arrTwo.length;
// iterate over array from the end
while (l--) {
// check value present in arrOne
if (arrOne.indexOf(arrTwo[l]) > -1)
// if present then remove and insert it
// at the beginning of arrThree
arrThree.unshift(arrTwo.splice(l, 1)[0])
}
console.log(arrTwo, arrThree);
Hi You can use filter function to filter array.
try with below code.
var arrOne = [1, 4, 7];
var arrTwo = [2, 3, 5, 1];
var arrThree = [];
function checkValue(a) {
return !arrOne.indexOf(a);
}
function checkValue2(a) {
return arrThree.indexOf(a);
}
function myFunction() {
arrThree = arrTwo.filter(checkValue);
document.getElementById("demo").innerHTML = arrThree ;
arrTwo = arrTwo.filter(checkValue2);
document.getElementById("demo1").innerHTML = arrTwo;
}
var arrOne = [1, 4, 7];
var arrTwo = [1, 2, 3, 4, 5];
var arrThree = diff(arrOne,arrTwo);//passes the two arrays
console.log(arrThree);
function diff(one, two){
one.forEach(function(e1){ //iterate through the first array
two.forEach(function(e2){//iterate through second
if(e1 == e2) //checking if elements are equal
two.pop(e2);//removing from second array
});
});
return two; //returning new array
}
You can use underscore js for easy array operations, the difference operation will be _.difference([1, 2, 3, 4, 5], [5, 2, 10]);.
var array1 = [1, 2, 3, 4, 5, 6],
var array2 = [1, 2, 3, 4, 5, 6, 7, 8, 9];
var common = $.grep(array1, function(element) {
return $.inArray(element, array2) !== -1;
});
console.log(common); // returns [1, 2, 3, 4, 5, 6];
array2 = array2.filter(function(obj) {
return array1.indexOf(obj) == -1;
});
// returns [7,8,9];
Since the arrays are sorted you could read them in parallel : O(n) instead of O(n2). Don't use a library for such a simple problem, this is overkill :-)
var i = 0, j = 0;
var a = [1, 4, 7];
var b = [1, 2, 3, 4, 5];
var c = [];
while (i < a.length && j < b.length) {
if (a[i] < b[j]) i++;
else if (a[i] > b[j]) j++;
else c.push(b.splice(j, 1)[0]);
}
console.log("a " + toString(a));
console.log("b " + toString(b));
console.log("c " + toString(c));
function toString (v) {
return "[ " + v.join(" ") + " ]";
}
Trace :
#0 init
a = [ 1 4 7 ]
i
b = [ 1 2 3 4 5 ]
j
c = []
#1 a[i] = b[j] => move b[j] to c
a = [ 1 4 7 ]
i
b = [ 2 3 4 5 ]
j
c = [ 1 ]
#2 a[i] < b[j] => increment i
a = [ 1 4 7 ]
i
b = [ 2 3 4 5 ]
j
c = [ 1 ]
#3 a[i] > b[j] => increment j
a = [ 1 4 7 ]
i
b = [ 2 3 4 5 ]
j
c = [ 1 ]
#4 a[i] > b[j] => increment j
a = [ 1 4 7 ]
i
b = [ 2 3 4 5 ]
j
c = [ 1 ]
#5 a[i] = b[j] => move b[j] to c
a = [ 1 4 7 ]
i
b = [ 2 3 5 ]
j
c = [ 1 4 ]
#6 a[i] < b[j] => increment i
a = [ 1 4 7 ]
i
b = [ 2 3 5 ]
j
c = [ 1 4 ]
#7 a[i] > b[j] => increment j
a = [ 1 4 7 ]
i
b = [ 2 3 5 ]
j
c = [ 1 4 ]
#8 j = length of b => done
I have converted a JavaScript spritesheet to a 2D integer array, and now I'm trying to split a 2D array of integers into multiple 2D arrays, using 1 as the "separator" number.
Is there any way to separate a 2D JavaScript array like the following into multiple arrays using a separator number, as shown below?
function separate2DArray(arrToSeparate, separator){
//separate the 2D array into multiple 2D arrays, using a
//specific number as the separator
}
//array to separate:
[
[5, 5, 5, 1, 5, 4, 5],
[5, 5, 4, 1, 4, 3, 4],
[1, 1, 1, 1, 1, 1, 1], //1 is the "separator number", which splits the array
[9, 2, 1, 4, 2, 4, 5], //horizontally and vertically
]
//The array above would produce the following 2D arrays:
5 5 5
5 5 4
5 4 5
4 3 4
9 2
4 2 4 5
The main application for this algorithm that I have in mind is spritesheet image separation.
Given that the separated areas are rectangular, this will work:
function separate2DArray(array, sep){
//separate the 2D array into multiple 2D arrays, using a
//specific number as the separator
var result = [],
currentSubs = {}; // using x coordinate as key
for (var y=0; y<array.length; y++) {
var line = array[y],
subBegin = 0;
for (var x=0; x<=line.length; x++) {
if (x == line.length || line[x] == sep) {
if (subBegin < x) {
var sub = line.slice(subBegin, x);
if (subBegin in currentSubs)
currentSubs[subBegin].push(sub);
else
currentSubs[subBegin] = [sub];
} else { // a line of separators, subBegin == x
if (subBegin in currentSubs) {
result.push(currentSubs[subBegin]);
delete currentSubs[subBegin];
}
}
subBegin = x+1;
}
}
}
for (var begin in currentSubs)
result.push(currentSubs[begin]);
return result;
}
The result here is just a very simple array of the subareas, without any information about their position in the original area. Improved version:
function separate2DArray(array, sep){
var result = [],
currentSubs = {};
for (var y=0; y<array.length; y++) {
var line = array[y],
subBegin = 0;
for (var x=0; x<=line.length; x++) {
if (x == line.length || line[x] == sep) {
if (subBegin < x) {
var subline = line.slice(subBegin, x);
if (! (subBegin in currentSubs)) {
var subarea = [];
result.push({x:x, y:y, area:subarea});
currentSubs[subBegin] = subarea;
}
currentSubs[subBegin].push(subline);
} else {
if (subBegin in currentSubs)
delete currentSubs[subBegin];
}
subBegin = x+1;
}
}
}
return result;
}
You would have to iterate through the array, capturing the preview entries into a sub array whenever you find a 1
http://jsfiddle.net/cWYpr/10/
var arr = [[5, 5, 5, 1, 5, 4, 5], [5, 5, 4, 1, 4, 3, 4], [1, 1, 1, 1, 1, 1, 1], [9, 2, 1, 4, 2, 4, 5]];
var twoD = [];
for (var x = 0; x < arr.length; x++) {
var row = arr[x];
var subArray = [], subArrays=[];
for (var y = 0; y < row.length; y++) {
if (row[y] == 1) {
if (subArray.length) subArrays.push(subArray.slice(0));
subArray = [];
}
else {
subArray.push(row[y]);
}
}
if (subArray.length) subArrays.push(subArray);
if(subArrays.length) twoD.push(subArrays);
}
console.log(twoD);
document.write(JSON.stringify(twoD));
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Split array into chunks
I am trying to convert an array of values into a new array of paired values.
For example i need to convert:
var arr = [1,2,3,4,5,6,7,8];
into:
arr = [[1,2], [3,4], [5,6], [7,8]];
I tried using jQuery's .map() method like so but this did not work for me:
arr= $.map(arr, function(n, i){
return [n + ',' + n[ i + 1 ]];
});
If you insist on using map, you could do it like this:
arr= $.map(arr, function(n, i){
if (i%2 === 0) return [[n, arr[ i + 1 ]]];
});
If you don't want to use a hammer on a thumbtack:
var arr = [1,2,3,4,5,6,7,8];
var newarr = new Array();
for (var i=0; i<arr.length; i=i+2) {
newarr.push(arr.slice(i,i+2));
}
don't use jquery for every problem:
var arr = [1, 2, 3, 4, 5, 6, 7, 8];
var narr = [];
for (i = 0; i < arr.length; i = i + 2) {
narr[i / 2] = [arr[i], arr[i + 1]];
}
but this only works if you have an even count of arr
Another example...
var arr = [1 , 2, 3, 4, 5, 6, 7, 8]
var final = []
while(arr.length) {
final.push(arr.splice(0, 2))
}
You don't want map, you want reduce.
Here is something that should work:
var endArr = [],
arr = [ 1, 2, 3, 4, 5, 6, 7, 8 ],
i = 0;
arr.reduce( function( prev, curr, index ) {
if ( index % 2 === 0 ) {
endArr[ i ] = [ prev, curr ];
}
i++;
} );
And just something else I thought about:
var endArr = [],
arr = [ 1, 2, 3, 4, 5, 6, 7, 8 ];
while ( arr.length ) {
endArr.push( arr.splice( 0, 2 ) );
}
Edit: Arf, it's the same solution as Chris Gutierrez.