Unset a Column in a Multidimensional Array

How to delete a column of a multidimensional array in php?

First when you do unset ($row[count($row)-2]); you are are just unsetting an index of the $row variable which is just a copy of the value from your array. So you are not deleting the value in the array.
Secondly, when you do $row[count($row)-2] you are assuming your $row has numerical indexes, which is not the case here. You want to delete the item_name index so you have to do something like unset($array[$index]['item_name']).

for($i = 0, $length = count($array); $i < $length; ++$i)
{
unset($array[$i]['item_name']);
}

How to remove multiple columns from the multi dimensional array?

You can try something like this:

$array = [
[
"picture_id" => "0",
"car_name" => "CA",
"from" => "2018",
"to" => "2020"
],
[
"picture_id" => "1",
"car_name" => "WA",
"from" => "2010",
"to" => "2019"
]
];

$whitelist = array("from", "to");
$finalArray = [];
foreach ($array as $k => $record) {
foreach ($record as $key => $item) {
if (!in_array($key, $whitelist)) {
$finalArray[$k][$key] = $item;
}
}
}
print("<pre>".print_r($finalArray,true)."</pre>");

What will print out:

Array
(
[0] => Array
(
[picture_id] => 0
[car_name] => CA
)

[1] => Array
(
[picture_id] => 1
[car_name] => WA
)

)

A short explanation...Basically you are looping over multi dimensional array as

foreach($array as $key => $value)

Where value is "inner" array, so in order to remove some elements from inner, and create a new multi dimensionalarray, you have to use keys, like in my example, from original array. So you than actually make an array like:

$newArray[$key] = $innerArray

And this gives you multi dimensional array.
BR

Remove a Column from a 2D Array

An array is a container of data that occupies a contiguous block of memory, its size should be defined when the array is being instantiated and can't be changed.

If you need an array of smaller or greater length, then you need to create a new one and copy all previously added elements that should be retained.

There's also no such thing in Java as "2D" arrays, we can create a nested array, i.e. an array containing other arrays.

And similarly to how we can reassign an integer value at a particular index in a plain array int[], we can change a reference in the array of arrays, i.e. we can make it point to another (newly created) array.

And that's what is required according to do in your assignment since the method is void. I.e. the given array needs to be changed by replacing all of its "rows", that greater or equal in length than the given column to remove col, with a new array that will retain all the previous element except for the one at index col.

private static void removeEntry(int[][] workArray, int col) {

for (int row = 0; row < workArray.length; row++) {

if (workArray[row].length <= col) { // no need to change anything
continue;
}

int newLength = workArray[row].length - 1;
int[] newRow = new int[newLength]; // creating a new row shorter by 1

for (int oldCol = 0, newCol = 0; oldCol < workArray[row].length; oldCol++, newCol++) {
if (oldCol == col) { // skipping the target column
newCol--; // newCol would be incremented automatically at the end of the iteration, but we want it to remain the same
continue;
}
newRow[newCol] = workArray[row][oldCol];
}

workArray[row] = newRow; // reassigning the row
}
}

main()

public static void main(String[] args) {
int[][] testArr =
{{1, 2},
{1, 2, 3},
{1, 2, 3, 4}};

removeEntry(testArr, 2);

// printing the testArr
for (int[] arr: testArr) {
System.out.println(Arrays.toString(arr));
}
}

Output:

[1, 2]
[1, 2]
[1, 2, 4]

A link to the Online Demo

If you've made the method to be void by mistake, you are required to return a new array, i.e. the return type int[] (check the requirements of your assignment carefully). Then a minor change needs to be applied to the logic explained and implemented above: every array should be replaced with a new one and then placed into the newly created resulting array.

Note Arrays.copyOf() allows creating a duplicate of the hole array, and System.arraycopy() can help you to copy the elements in the given range from one array into another, but because you are working on an assignment I suggest you to do it manually with loops because you are expected to demonstrate the knowledge on how to manipulate with arrays, not the knowledge of special utility features (unless otherwise specified in the assignment).

private static int[][] removeEntry(int[][] workArray, int col) {
int[][] result = new int[workArray.length][];

for (int row = 0; row < workArray.length; row++) {

int newLength = col < workArray[row].length ? workArray[row].length - 1 : workArray[row].length;
int[] newRow = new int[newLength];

for (int oldCol = 0, newCol = 0; oldCol < workArray[row].length; oldCol++, newCol++) {
if (oldCol == col) {
newCol--;
continue;
}
newRow[newCol] = workArray[row][oldCol];
}

result[row] = newRow; // reassigning the row
}

return result;
}

main()

public static void main(String[] args) {
int[][] testArr =
{{1, 2},
{1, 2, 3},
{1, 2, 3, 4}};

int[][] newArr = removeEntry(testArr, 2);

// printing the testArr
for (int[] arr: newArr) {
System.out.println(Arrays.toString(arr));
}
}

Output:

[1, 2]
[1, 2]
[1, 2, 4]

A link to the Online Demo

Deleting particular column from a multidimensional array in javascript

You could specify the index and then iterate over the array and splice the inner arrays.

var array = [["a", "b", "c", "d", "e", "f"], ["a", "b", "c", "d", "e", "f"], ["a", "b", "c", "d", "e", "f"]],    index = 1;
array.forEach(a => a.splice(index, 1));
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }

How to delete column in 2d array c++ with dynamic array?

For starters the variable index is set to a row number

index = i;

Then this row is deleted

delete [] arr[index];

But you are going to remove a column instead of a row. So this code does not make a sense.

Also you are incorrectly searching the maximum element. If the user will enter all negative values then the maximum value will be equal to 0 though an element with such value is not present in the array.

In this declaration

int** tmp = new int*[index - 1];

you allocated an array with rows that one less than the number of rows in the original array. Moreover if index is equal to 0 then there is allocated a very large extent of memory.

This statement

delete [] arr;

produces a memory leak.

It seems what you need is something like the following

#include <iostream>

int main()
{
size_t row = 3, col = 3;

int **arr = new int * [row];

for ( size_t i = 0; i < row; i++ )
{
arr[i] = new int[col];
}

for ( size_t i = 0; i < row; i++ )
{
for ( size_t j = 0; j < col; j++ )
{
std::cin >> arr[i][j];
}
}

for ( size_t i = 0; i < row; i++ )
{
for ( size_t j = 0; j < col; j++ )
{
std::cout << arr[i][j] << " ";
}
std::cout << std::endl;
}

std::cout << "------------- " << std::endl;

size_t max_i = 0, max_j = 0;

for ( size_t i = 0; i < row; i++ )
{
for ( size_t j = 0; j < col; j++ )
{
if ( arr[max_i][max_j] < arr[i][j] )
{
max_i = i; max_j = j;
}
}
}

int **tmp = new int*[row];
for ( size_t i = 0; i < row; i++ )
{
tmp[i] = new int[col-1];
}

for ( size_t i = 0; i < row; i++ )
{
for ( size_t j = 0, k = 0; j < col; j++ )
{
if ( j != max_j ) tmp[i][k++] = arr[i][j];
}
}

for ( size_t i = 0; i < row; i++ )
{
delete [] arr[i];
}

delete [] arr;

arr = tmp;

--col;

for ( size_t i = 0; i < row; i++ )
{
for ( size_t j = 0; j < col; j++ )
{
std::cout << arr[i][j] << " ";
}
std::cout << std::endl;
}

for ( size_t i = 0; i < row; i++ )
{
delete [] arr[i];
}

delete [] arr;

return 0;
}

The program output might look like

1 2 3 
6 5 4
7 9 8
-------------
1 3
6 4
7 8

How to delete a column in 2d array in c++

You can not remove a column from an array. But you can move all elements of columns to the left filling the "deleted" column and keep the number of actual columns of the array.

Here is a demonstrative program. In the program the variable n stores the number of actual columns of a two-dimensional array.

#include <iostream>
#include <string>
#include <type_traits>
#include <iterator>
#include <algorithm>

template <typename T>
bool remove_column( T &a, size_t n, size_t pos )
{
const size_t N =
std::extent<typename std::remove_reference<decltype( a )>::type, 1>::value;

bool success = n <= N && pos < n;

if ( success )
{
for ( auto &row : a )
{
std::copy( std::next( std::begin( row ), pos + 1 ),
std::next( std::begin( row ), n ),
std::next( std::begin( row ), pos ) );
}
}

return success;
}

int main()
{
const size_t M = 4;
const size_t N = 5;
std::string a[M][N] =
{
{ "A0", "B0", "C0", "D0", "E0" },
{ "A1", "B1", "C1", "D1", "E1" },
{ "A2", "B2", "C2", "D2", "E2" },
{ "A3", "B3", "C3", "D3", "E3" },
};

size_t n = N;

for ( const auto &row : a )
{
for ( size_t i = 0; i < n; i++ )
{
std::cout << row[i] << ' ';
}
std::cout << '\n';
}

std::cout << '\n';

if ( remove_column( a, n, 0 ) ) --n;

for ( const auto &row : a )
{
for ( size_t i = 0; i < n; i++ )
{
std::cout << row[i] << ' ';
}
std::cout << '\n';
}

std::cout << '\n';

if ( remove_column( a, n, n - 1 ) ) --n;

for ( const auto &row : a )
{
for ( size_t i = 0; i < n; i++ )
{
std::cout << row[i] << ' ';
}
std::cout << '\n';
}

std::cout << '\n';

if ( remove_column( a, n, 1 ) ) --n;

for ( const auto &row : a )
{
for ( size_t i = 0; i < n; i++ )
{
std::cout << row[i] << ' ';
}
std::cout << '\n';
}

std::cout << '\n';

return 0;
}

The program output is

A0 B0 C0 D0 E0 
A1 B1 C1 D1 E1
A2 B2 C2 D2 E2
A3 B3 C3 D3 E3

B0 C0 D0 E0
B1 C1 D1 E1
B2 C2 D2 E2
B3 C3 D3 E3

B0 C0 D0
B1 C1 D1
B2 C2 D2
B3 C3 D3

B0 D0
B1 D1
B2 D2
B3 D3

Or the function can be defined the following more simpler way

template <typename T, size_t M, size_t N>
bool remove_column( T ( &a )[M][N], size_t n, size_t pos )
{
bool success = n <= N && pos < n;

if ( success )
{
for ( auto &row : a )
{
std::copy( std::next( std::begin( row ), pos + 1 ),
std::next( std::begin( row ), n ),
std::next( std::begin( row ), pos ) );
}
}

return success;
}

In this case the header <type_traits> is redundant.

Also instead of the algorithm std::copy you could use the algorithm std::move.



Related Topics



Leave a reply



Submit