How to remove row in 2d array in javascript - javascript

How to remove row in two dimensional array in JavaScript with row number. If I want to delete all elements in row number 4 then how can do it??

Here's an example of how to remove a row by using splice:
var array = [];
var count = 0;
for (var row=0; row<4; row++) {
array[row] = [];
for (var col=0; col<5; col++) {
array[row][col] = count++;
}
}
console.log(array);
[ [ 0, 1, 2, 3, 4 ],
[ 5, 6, 7, 8, 9 ],
[ 10, 11, 12, 13, 14 ],
[ 15, 16, 17, 18, 19 ] ]
function deleteRow(arr, row) {
arr = arr.slice(0); // make copy
arr.splice(row - 1, 1);
return arr;
}
console.log(deleteRow(array, 4));
[ [ 0, 1, 2, 3, 4 ],
[ 5, 6, 7, 8, 9 ],
[ 10, 11, 12, 13, 14 ] ]

Lets say you have an array 'arr' then you can remove full row by arr.splice(3,1);

I realize this question is old, but it is one of the first results when searching for how to remove from a 2d (multidimensional) array in JS.
Here is what I used to delete the inner array based on a key of the inner array. It should continue to work if there were multiple instances of the same key. In this example, I am searching for, and removing the array with the key of 18.
Sorry about the formatting - it gets the point across.
var items = [
["19", 1],
["18", 2],
["20", 3]
];
//console.log(items);
document.getElementById("a").innerHTML = items;
for (var i = 0; i < items.length; i++) {
if (items[i][0] == "18") {
items.splice(i, 1);
}
}
//console.log(items);
document.getElementById("b").innerHTML = items;
<p>Before</p>
<div id='a'></div>
<p>After</p>
<div id='b'></div>

Just call the splice(4, 1) method, when 4 is row number and 1 is number of rows to remove -
twoDimensionalArray.splice(4, 1); // remove 4th row
Also shift() and pop() are very handy methods which remove first and last rows accordingly -
twoDimensionalArray.shift(); // to remove first row
twoDimensionalArray.pop(); // to remove last row

Here you have a visual example of a bidimensional array with row deletion button (delete by ID) + jQuery preview of the table.
I hope it can be usefull!
JS DELETE ROW from Bidimensional ARRAY + Show on jQuery Cart Table https://jsbin.com/xeqixi/edit?html,js,output

delete array[index];
array.length--;
In your case give index as 4 and execute the above statement and you need to manually reduce the length of array.

Related

elements are being added to every row when inserting into a row for a 2D array that has been filled with empty Arrays

I am creating a new matrix where I want to take the rows of the original matrix and make them into columns as well as take the columns of the original matrix and make them into rows.
A matrix of:
[[1,2]
[3,4] [[1,3,5]
[5,6]] turns into [2,4,6]]
When I initialize the new matrix while using the fill() method to create my rows, the insertions duplicate for every row when inserting into a row.
const arrOne = [[1,2,3],[4,5,6],[7,8,9]]
var transpose = function(matrix) {
const transposedArr = new Array(matrix[0].length).fill(new Array()); // initializes array to [ [], [], [] ]
//iterate through row
for(let i = 0; i < matrix.length; i++) {
//iterate through columns at row
for(let j = 0; j < matrix[i].length; j++) {
transposedArr[j].push(matrix[i][j])
}
}
return transposedArr;
};
console.log(transpose(arrOne));
This will print
[
[1, 2, 3, 4, 5, 6, 7, 8, 9],
[1, 2, 3, 4, 5, 6, 7, 8, 9],
[1, 2, 3, 4, 5, 6, 7, 8, 9],
]
When I initialize my array using a for loop, I do not get duplicate entries
const arrOne = [[1,2,3],[4,5,6],[7,8,9]]
var transpose = function(matrix) {
const transposedArr = [] // initializing using const transposedArr = Array() also works!
for(let i = 0; i < matrix[0].length; i++) { // initializes array to [ [], [], [] ]
transposedArr.push(new Array())
}
//iterate through row
for(let i = 0; i < matrix.length; i++) {
//iterate through columns at row
for(let j = 0; j < matrix[i].length; j++) {
transposedArr[j].push(matrix[i][j])
}
}
return transposedArr;
};
console.log(transpose(arrOne));
This will print:
[
[ 1, 4, 7 ],
[ 2, 5, 8 ],
[ 3, 6, 9 ]
]
ASK: Why is it that when I initialize the array using the fill() method, it is duplicating my insertions for each row?
I came across this issue when working on this Leetcode problem: https://leetcode.com/problems/transpose-matrix/
I also tested this code in repl. It was to make sure it wasn't an issue in Leetcode's environment.
const matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
/* Allocate newMatrix array */
const newMatrix = [];
for (const i in matrix) {
const temp = [];
for (const j in matrix[i])
temp.push(matrix[j][i]);
newMatrix.push(temp);
}
console.log(newMatrix);
First of all, I have created and new array with the opposite length from the first array (Rows = Cols / Cols = Rows).
Then you just have to initialize the second array with [i][j] = [j][i] so it will initialize the column of the original matrix to the row of the new one.
Hope you understood.
By the way fill method "fills" the array element to a STATIC value, and the parameters should be (value, start, end).
Documentation: Array.prototype.fill()

Randomly group elements of array using Javascript

I have JSON file, from which I display the data:
data: [
{
name: "john"
},
{
name: "lora"
},
...
]
In total I have 16 names. What I want to do is to randomly group this array by 4 people, total 4 groups.
What is the best way to do this using react.js?
I don't think a solution to this is React-specific, just vanilla javascript will do. First, randomize your entire array (How to randomize (shuffle) a JavaScript array? has a couple different answers you could use). Then, it should be pretty straightforward to iterate over the array and break each group of 4 successive names out.
Here's a simple example with everything built into one function (comments included to explain what's going on):
const data = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
function randomizeAndSplit(data, chunkSize) {
var arrayOfArrays = [];
var shuffled = [...data]; //make a copy so that we don't mutate the original array
//shuffle the elements
for (let i = shuffled.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
}
//split the shuffled version by the chunk size
for (var i=0; i<shuffled.length; i+=chunkSize) {
arrayOfArrays.push(shuffled.slice(i,i+chunkSize));
}
return arrayOfArrays;
}
console.log(randomizeAndSplit(data, 4))
//Example output: [[13, 7, 2, 14], [9, 12, 8, 15], [1, 16, 10, 3], [11, 6, 5, 4]]

Issue trying to find length of sequence in an array

I'm trying to find the length of the sequence in an array, between the first and the second occurance of a specified number.
For Example: lengthOfSequence([0, -3, 7, 4, 0, 3, 7, 9], 7) would return 5, because there are 5 indices between the first and second occurrence of the number 7.
I feel like the code that I have written should work, but after console logging it looks as if my arr.push() method is only pushing the first index to my indexes array variable, and its pushing it twice. Why would this be happening?
Here is my code for context:
var lengthOfSequence = function (arr, n) {
var indexes = [];
for (var i = 0; i < arr.length; i++) {
if (arr[i] === n) {
indexes.push(arr.indexOf(arr[i]));
}
}
return arr.indexOf(indexes[1]) - arr.indexOf(indexes[0]);
}
So, for example, if I use my array that I used earlier lengthOfSequence([0, -3, 7, 4, 0, 3, 7, 9], 7), my for loop would find the first occurrence of 7 (index 2) and push it to my index array variable, but it would just do it twice. So my indexes array would just be [2,2]. Why would it not be [2,6]?
indexOf does not do what you think it does. It returns the index of the first item that it finds with the provided value. For both values in the array, it returns that first index.
Since you want the index only and you are already iterating over it with your loop, you can simply use i itself:
indexes.push(i);
You may do it as follows but don't know why it is 5 that you want. I guess it should be 4. OK lets make it 5.
function lengthOfSequence(a,f){
var fi = a.indexOf(f);
return a.slice(fi)
.indexOf(f)+(2*fi+1);
}
var a = [0, -3, 7, 4, 0, 3, 7, 9],
f = 7;
console.log(lengthOfSequence(a,f));
You could use just the index and return the difference between the last element of indices and the first one plus one.
var lengthOfSequence = function(arr, n) {
var indexes = [];
for (var i = 0; i < arr.length; i++) {
if (arr[i] === n) {
indexes.push(i);
}
}
return indexes[indexes.length - 1] - indexes[0] + 1;
}
console.log(lengthOfSequence([0, -3, 7, 4, 0, 3, 7, 9], 7)); // 5
console.log(lengthOfSequence([0, -3, 7, 4, 0, 3, 7, 9], -3)); // 1

Creating a new array that counts the distance between specific numbers

This is easy to mis-explain so I'll simplify it. Let's say I have an array that are the results of dice throws. Like:
1 2 4 6 1 2 6 6 2 4 etc
Every time you throw a 6, you win. I want to create a new array which contains after how many turns you would win based on the original array. So the above array would create an array that is:
4 3 1
(it takes 4 turns to win, then 3, then 1)
So I only want to count the distance between the 6's. (I could also convert the dice results to binary win/lose)
How do I do this in excel? (or javascript, but really prefer excel)
Create a Helper Column (Column A of Excel). Put 1 in the first cell (A2) of Helper column. Follow it up with the formula (in A3) =IF(B3=6,A2+1,A2).Drag it to the last row of to the given array.
Then Create a Result column (Column C of Excel). Type in formula (in C2)
=IF(ROW()-1=MAX(A:A),"",IF(IF(ROW()-1=1,COUNTIF(A:A,ROW()-1)+1,COUNTIF(A:A,ROW()-1))=0,"",IF(ROW()-1=1,COUNTIF(A:A,ROW()-1)+1,COUNTIF(A:A,ROW()-1))))
in the first cell of Result Column (Column C of Excel). Drag and get the required result.
Hide Helper Column.
Note: Array Data starts from cell B2
If the first array is B1:K1 the second might be created with:
=IF(B1=6,COLUMN()-SUM(A2:$B2)-1,"")
in B2 and copied across to suit.
This might work for you:
var rollsUntil6 = function(rolls) {
return rolls.reduce(function(indices, roll, idx) {
if (roll == 6) {indices.push(idx);} return indices;
}, [-1]).map(function(val, idx, arr) {
return val - arr[idx - 1];
}).slice(1);
};
rollsUntil6([1, 2, 4, 6, 1, 2, 6, 6, 2, 4]); //=> [4, 3, 1]
What you need to do is iterate over the array and count the spaces by accumulating into a collector variable. You can find the code below it just pops into and alert window.(Javascript)
var array = [1, 2, 4, 6, 1, 2, 6, 6, 2, 4]
var resultArray = []
var i = 0;
var distance = 0;
for (i = 0; i < array.length; i++) {
distance++;
if (array[i] == 6) {
resultArray.push(distance);
distance = 0;
}
}
alert(resultArray);
I took an attempt at doing in excel.
You can place a command button and define a sub function like below and you will get the results expected. For instructions on how to place a command button http://www.excel-easy.com/vba/create-a-macro.html#command-button
Sub DistanceOf6InString(x As String)
Size = Len(x)
distance = 0
result = ""
Dim i As Integer
For i = 1 To Size
distance = distance + 1
If (Mid(x, i, 1) = "6") Then
result = result & distance
distance = 0
End If
Next i
MsgBox result
End Sub
Private Sub CommandButton1_Click()
DistanceOf6InString ("1246126624")
End Sub
You can repeatedly find the array.indexOf(6,lastmatch)
var array= [1, 2, 4, 6, 1, 2, 6, 6, 2, 4];
var resultArray= [], i, incr= 0;
while((i= array.indexOf(6, incr))!= -1){
i+= 1;
resultArray.push(i-incr);
incr= i;
}
resultArray returned value: (Array) [4,3,1]

Explaination needed: Different outputs when used for...in and for(;;) in JavaScript

In NodeJS, I created the following two scripts, both of them was intended to remove even numbers from an array.
This is my 1st script:
#!/usr/bin/nodejs
var myarr = [2,3,5,1,6,2,28,5,7,90,3];
console.log(myarr);
for(var i in myarr){
if(myarr[i] % 2 == 0){
myarr.splice(i,1);
--i;
}
}
console.log(myarr);
Output for the first script was following:
[ 2, 3, 5, 1, 6, 2, 28, 5, 7, 90, 3 ]
[ 3, 5, 1, 2, 5, 7, 3 ]
In 2nd script, I changed for..in loop to for(;;) loop as follows:
#!/usr/bin/nodejs
var myarr = [2,3,5,1,6,2,28,5,7,90,3];
console.log(myarr);
for(var i=0;i<myarr.length;i++){
if(myarr[i] % 2 == 0){
myarr.splice(i,1);
--i;
}
}
console.log(myarr);
I got following output for the 2nd script:
[ 2, 3, 5, 1, 6, 2, 28, 5, 7, 90, 3 ]
[ 3, 5, 1, 5, 7, 3 ]
Although my intention was the same, two for loops gave me different outputs. I figured out that, in my first script, if there are two adjacent even numbers exist in the original array, if condition seems to be applied for the first even number only where the second even number is skipped. I would really appreciate if anybody can explain this difference clearly.
What you're doing is wrong. You're removing keys from the array whilst looping through the same array. Your for...in loop will only ever perform 7 iterations, as 4 of your keys are spliced from the array whilst the array is still being iterated through, whereas your for(;;) loop will always perform all 11 iterations as this is defined at the beginning (myarr.length).
You should define a second array to use for your results instead:
for...in
var myarr = [2,3,5,1,6,2,28,5,7,90,3],
resultarr = [];
console.log(myarr);
for(var i in myarr){
if(myarr[i] % 2 != 0){
resultarr.push(myarr[i])
}
}
console.log(resultarr);
-> [3, 5, 1, 5, 7, 3]
for(;;)
var myarr = [2,3,5,1,6,2,28,5,7,90,3],
resultarr = [];
console.log(myarr);
for(var i=0;i<myarr.length;i++){
if(myarr[i] % 2 != 0){
resultarr.push(myarr[i]);
}
}
console.log(resultarr);
-> [3, 5, 1, 5, 7, 3]
As an ending note, you shouldn't use the for...in loop for iterating through arrays anyway. This answer details why this is a bad idea.

Categories

Resources