How to iterate only on part of 2D array in JavaScript? - javascript

I have 2D array
var arr = [[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, 26, 27, 28, 29],
[30, 31, 32, 33, 34, 35]];
Now we are dividing this into smaller parts like 2x2. How to iterate only on part (block) of this array e.g: items with indexes arr[2][4], arr[2][5], arr[3][4], arr[3][5]?
Edit:
Seems question is not easy understandable. I want to iterate over blocks.
var blocks = 9;
var output = '';
for( var block = 0; block < blocks; block++) {
// actual iteration over array
for(var i = ... ) {
for(var j = ... ) {
output += arr[i][j] + ' ';
}
}
console.log(output);
output = '';
}
Expected output would be:
0 1 6 7
2 3 8 9
4 5 10 11
12 13 18 19
14 15 20 21
16 17 22 23
24 25 30 31
26 27 32 33
28 29 34 35

You need to nest for loops.
var arr = [[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, 26, 27, 28, 29],
[30, 31, 32, 33, 34, 35]];
function loopThrough() {
for(int i = 0; i < arr.length; i++) {
// this will give you arr[0], arr[1], etc.
for(int j = 0; j < arr.length; j++) {
// this will give you arr[0][0], arr[0][1], etc.
console.log(arr[i][j]);
}
}
}
loopThrough();
If you want it to loop over only the last 2, then set j] = arr[i].length-2
<script type="text/javascript">
var arr = [[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, 26, 27, 28, 29],
[30, 31, 32, 33, 34, 35]];
function loopThrough() {
for(var i = 0; i < arr.length; i++) {
// this will give you arr[0], arr[1], etc.
for(var j = arr[i].length-2; j < arr[i].length; j++) {
// this will give you arr[0][0], arr[0][1], etc.
console.log(arr[i][j]);
}
}
}
loopThrough();
</script>

function subblock_array(arr, startX, endX, startY, endY) {
var subArr = [];
for (var ii=startX; ii<endX; ii++) {
subArrY = [];
for (var jj=startY; jj<endY; jj++) {
subArrY.push(arr[ii][jj]);
}
subArr.push(subArrY);
}
return subArr;
}
subblock_array(arr, 2, 4, 4, 6)

You want to access those indexes in order :
arr[0][0] arr[0][1] arr[1][0] arr[1][1]
arr[0][2] arr[0][3] arr[1][2] arr[1][3]
[...]
arr[0][y-1] arr[0][y] arr[1][y-1] arr[1][y] // first two lines processed
arr[2][0] arr[2][1] arr[3][0] arr[3][1] // we continue with the next two lines
[...]
arr[2][y-1] arr[2][y] arr[3][y-1] arr[3][y]
[...]
arr[x-1][0] arr[x-1][1] arr[x][0] arr[x][1]
[...]
arr[x-1][y-1] arr[x-1][y] arr[x][y-1] arr[x][y]
As you can see we have two levels of iteration : a first one iterates over the lines, skipping every other one, and a second one iterates over the columns, skipping every other one.
The following code should implement this :
for (var x=0; x < arr.length; x+=2) {
for (var y=0; y < arr[x].length; y+=2) {
console.log(arr[x][y] + " " + arr[x][y+1] + " " + arr[x+1][y] + " " + arr[x+1][y+1]);
}
}
You will notice that we increment the iterations variables by two each loop, since the inner block consumes two columns and lines at once.

You would need a loop with an offset inner loop to iterate over the last two positions. Something like this would work, you can see the results on this js fiddle: https://jsfiddle.net/0wfysb38/3/
var arr = [[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, 26, 27, 28, 29],
[30, 31, 32, 33, 34, 35]];
for(i = 0; i < arr.length - 1; i=i+2) {
for(j = 0; j < arr[i].length - 1; j=j+2) {
strOut = '';
strOut = strOut + ', ' +arr[i][j];
strOut = strOut + ', ' +arr[i][j+1];
strOut = strOut + ', ' +arr[i+1][j];
strOut = strOut + ', ' +arr[i+1][j+1];
strOut = strOut.substring(1,strOut.length)
console.log(strOut);
}
}
Edit: Updated to code to produce results matching the expected output. The key is to iterate the loops by 2, and seek the next position in the array by offsetting. This is not very flexible, and the array this loops over should be structured appropriately.

Related

I want to compare numbers after each iteration and return common number [duplicate]

This question already has answers here:
How to calculate intersection of multiple arrays in JavaScript? And what does [equals: function] mean?
(18 answers)
Closed 1 year ago.
How can I get one common number in each iteration for example :
2 ==> 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 36 ... 60
3 ==> 6 9 12 15 18 21 24 27 30 33 36 39 42 45 48 51 54 57 60
4 ==> 8 12 16 20 24 28 32 36 40 44 48 52 56 60
I want to loop through 2,3,4 and pause the loop if we get the same number in all elements.
Thank you in advance.
function smallestCommons(array) {
let arr = array.sort()
let newArr = [];
for(let i = arr[0]; i <= arr[1]; i++){
console.log('when i = ', i);
for(let j = i; j <= arr[1]; j+= i){
console.log(j)
}
}
return newArr;
}
var arr1=[4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,36],
arr2 =[6,9,12,15,18,21,24,27,30,33,36,39,42,45,48,51,54,57,60],
arr3 =[8,12,16,20,24,28,32,36,40,44,48,52,56,60];
//Below code finds common numbers from the above 3 arrays and add that number in newArr
//and newArr values are printed at the end
var newArr=[];
for(let i =0; i < arr1.length; i++){
if(arr2.includes(arr1[i]) && arr3.includes(arr1[i]) ){
newArr.push(arr1[i]);
}
}
console.log(newArr)
I modified your code a bit.
You can use this:
var arr1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 3];
var arr2 = [8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56, 60, 12];
var arr3 = [6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48, 51, 54, 57, 60];
var arr4 = [4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 36];
var arr5 = [6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48, 51, 54, 57, 60];
var arr6 = [8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56, 60];
function smallestCommons(...arrays) {
// let arr = array.sort();
var newarr = [];
var duplicates = [];
for (var i = 0; i < arrays.length; i++) {
newarr = newarr.concat(arrays[i]);
}
newarr = newarr.sort(function(a, b) {
return a - b
});
for (var i = 0; i < newarr.length; i++) {
if (i > 0 && newarr[i] == newarr[i - 1] && !duplicates.includes(newarr[i])) {
duplicates.push(newarr[i]);
}
}
return duplicates.sort(function(a, b) {
return a - b
});
}
console.log(smallestCommons(arr1, arr2, arr3));

i writing a besic code for finding premium customer who ordered quantity is equal or more then 5 and amount in also more then 20rs in javascript

customers_data = {
'Ben10': [22, 30, 11, 17, 15, 52, 27, 12],
'Sameer': [5, 17, 30, 33, 40, 22, 26, 10, 11, 45],
'Zeeshan': [22, 30, 11, 5, 17, 30, 6, 57]
}
var cus = Object.keys(customers_data);
var count = 0;
for (var j = 0; j < cus.length; j++) {
console.log(cus[j]);
for (var i = 0; i < customers_data.cus[j].length; i++) {
if (customers_data.cus[j][i] > 20) {
count++;
colsole.log(cus[j][i])
}
}
if (count >= 5) {
console.log(cus[j] + "is prime customer")
} else {
console.log('count of order is' + count)
}
}
You need to move the count variable, at least the initialization with zero inside of the outer loop.
The second propblem, you need to access the property with the value in bracket notation (property accessor).
customers_data[cus[j]]
var customers_data = { Ben10: [22, 30, 11, 17, 15, 52, 27, 12], Sameer: [5, 17, 30, 33, 40, 22, 26, 10, 11, 45], Zeeshan: [22, 30, 11, 5, 17, 30, 6, 57] },
cus = Object.keys(customers_data);
for (var j = 0; j < cus.length; j++) {
let count = 0;
for (var i = 0; i < customers_data[cus[j]].length; i++) {
if (customers_data[cus[j]][i] > 20) count++;
}
console.log('count of order is ' + count)
if (count >= 5) {
console.log(cus[j] + " is prime customer")
}
}

Javascript function remove from position in array

I have an array:
var myArray = [12, 11, 13, 18, 30, 51, 21, 18, 20];
I need to remove each 3rd item from the array and add it to another array.
The final result should be:
var myArray = [12, 11 18, 30, 21, 18];
var secondArray = [13, 51, 20];
How can i do that?
iterate over the array and splice every 3rd element and push to the second array.
var myArray = [12, 11, 13, 18, 30, 51, 21, 18, 20];
var secondArray = [];
for (var i = 2; i < myArray.length; i += 2) {
secondArray.push(myArray[i]);
myArray.splice(i, 1);
}
console.info('myArray', myArray)
console.info('secondArray', secondArray)
I do not like example with splicing source array, because splicing is a long operation and in large arrays / multiple operations it will be not so effective. I think you should create new arrays and don't mind.
const arraysList = myArray.reduce((acc, item, index) => {
if ((index + 1) % 3 === 0) {
acc.second.push(item);
} else {
acc.first.push(item);
}
return acc;
}, { first: [], second: [] })
console.log(arraysList.first); // [12, 11 18, 30, 21, 18]
console.log(arraysList.second); // [13, 51, 20]
var myArray = [12, 11, 13, 18, 30, 51, 21, 18, 20];
var newArray1 = [];
var newArray2 = [];
myArray.forEach(function(value,index){
if((index + 1) % 3 === 0){
newArray1.push(value);
}
else {
newArray2.push(value);
}
});
console.log(newArray1); // Stores element at index 3 in the original array
console.log(newArray2); // Stores element at index other than 3 in the original array
Array#reduce the original array into 2 new arrays:
const myArray = [12, 11, 13, 18, 30, 51, 21, 18, 20];
const [without3rdItems, with3rdItems] = myArray.reduce((arrs, n, i) => {
const arr = (i + 1) % 3 ? 0 : 1;
arrs[arr].push(n);
return arrs;
}, [[], []]);
console.log(without3rdItems.join());
console.log(with3rdItems.join());
var a = [12, 11, 13, 18, 30, 51, 21, 18, 20];
var b = [ ];
var l = a.length;
for(i = 2; i < l; i += 2){
b.push(a[i]);
a.splice(i, 1);
l--;
}
console.log("Array a: ", a);
console.log("Array b: ", b);

Split javascript array of numbers into ranges

I have an array such as:
[16, 20, 1, 4, 6, 8, 9, 22, 18, 14, 13, 12]
That I would like split into 6 different arrays based on ranges 1-4, 5-8, 9-12, 13-16, 17-20, 21-24.
What is the simplest way to do this with javascript?
You could use an interval for assigning the numbers to a specific slot.
var array = [16, 20, 1, 4, 6, 8, 9, 22, 18, 14, 13, 12],
interval = 4,
result = array.reduce(function (r, a) {
var slot = Math.floor((a - 1) / interval);
(r[slot] = r[slot] || []).push(a);
return r;
}, []);
console.log(result);
The solution using Array.prototype.filter() function:
var list = [16, 20, 1, 4, 6, 8, 9, 22, 18, 14, 13, 12], i
result = [];
// considering ranges `1-4, 5-8, 9-12, 13-16, 17-20, 21-24`
for (i = 1; i < 24; i+= 4) {
result.push(list.filter(function(d){
return ((i+4 > d) && d >= i); // check if the number between lower and upper bound
}));
}
console.log(result);
Simplest answer:
var numbers = [16, 20, 1, 4, 6, 8, 9, 22, 18, 14, 13, 12];
var array1 = []; // range 1-4
var array2 = []; // range 5-8
for(var i=0; i< numbers.length; i++) {
if(numbers[i]>= 1 && numbers[i] <= 4) {
array1[i] = numbers[i]
} else if(numbers[i]>= 5 && numbers[i] <= 8) {
array2[i] = numbers[i]
}
//... continue for remaining ranges
}

Going on a new line when the array reaches a number higher than x

The issue is as followed: i'm trying to make a piece of code that will print all the elements of an array until it reaches an number higher than 30 lets say. When it does reach that number, the code should start on a new line.
For example, i have the array:
[5, 34, 8, 31, 7, 5, 4, 39, 9, 10, 11, 32, 14];
When the code is finished, it should print something like this:
5, 34
8, 31
7, 5, 4, 39
9, 10, 11, 32
14
All i've been able to do so far is:
var array1 = [5, 34, 8, 31, 7, 5, 4, 39, 9, 10, 11, 32, 14];
for (i = 0; i < array1.length; i++){
}
I have no idea how would i continue from here. I've tried different stuff that came through my mind, but nothing worked. Could someone explain? I'm not here just for the solving, but more for the explanation.
Thank you.
Assuming you are writing to the console:
var array1 = [5, 34, 8, 31, 7, 5, 4, 39, 9, 10, 11, 32, 14];
var value = '';
for (var i = 0; i < array1.length; i++) {
var number = array1[i];
value += value.length > 0 ? ',' + number : number;
if (number > 30) {
console.log(value);
value = '';
}
}
console.log(value);
this will print to the console this result:
5,34
8,31
7,5,4,39
9,10,11,32
14
value is appended to within every iteration of the loop. If the current number is over 30 then value is written to the console. After value is written to the console it is cleared.
I assume this is what you want :
function printArray(arr){
for(var i =0;i<arr.length;i++){
if( arr[i] > 30){
console.log('\n');
}
console.log(arr[i]);
}
printArray([5, 34, 8, 31, 7, 5, 4, 39, 9, 10, 11, 32, 14]);

Categories

Resources