Removing all column elements in a two-dimensional array

I have this array:

arr = [["a","b","c"],[2,3,5],[3,6,8],[1,3,1]] 

which represents a shrimp table containing the columns "a", "b" and "c".

How to delete the entire column "c" with all its values, 5, 8, 1?

There may be helpful hints in โ€œ Creating two-dimensional arrays and accessing additional arrays in Ruby โ€ and โ€œ difficulties modifying a two-dimensional ruby โ€‹โ€‹arrayโ€ , but I cannot transfer them to my problem.

+4
source share
8 answers

Just out of curiosity - here is another approach (single line):

 arr.transpose[0..-2].transpose 
+6
source

Since this is only the last value, you can use Array#pop :

 arr.each do |a| a.pop end 

Or find the index "c" and delete all the elements in this index:

 c_index = arr[0].index "c" arr.each do |a| a.delete_at c_index end 

Or using map :

 c_index = arr[0].index "c" arr.map{|a| a.delete_at c_index } 
+2
source
  arr = [["a","b","c"],[2,3,5],[3,6,8],[1,3,1]] i = 2 # the index of the column you want to delete arr.each do |row| row.delete_at i end => [["a", "b"], [2, 3], [3, 6], [1, 3]] class Matrix < Array def delete_column(i) arr.each do |row| row.delete_at i end end end 
+1
source
 arr.map { |row| row.delete_at(2) } #=> ["c", 5, 8, 1] 

This is if you really want to delete the last column so that it is no longer in the original array. If you just want to return it, leaving arr intact:

 arr.map { |row| row[2] } #=> ["c", 5, 8, 1] 

If you want to delete all items in a column matching a specific heading:

 if index = arr.index('c') then arr.map { |row| row[index] } # or arr.map { |row| row.delete_at(index) } end 
+1
source
 # Assuming first row are headers arr = [["a","b","c"],[2,3,5],[3,6,8],[1,3,1]] col = arr.first.index "c" arr.each { |a| a.delete_at(col) } 
+1
source

Assuming the first element of the array is always an array of column names, you can do the following:

 def delete_column(col, array) index = array.first.index(col) return unless index array.each{ |a| a.delete_at(index) } end 

It will change the passed array. You should not assign your result to anything.

0
source
 arr = [["a","b","c"],[2,3,5],[3,6,8],[1,3,1]] arr.map(&:pop) p arr #=> [["a", "b"], [2, 3], [3, 6], [1, 3]] 
0
source

I had a more general need to remove one or more s columns that matched the text pattern (and not just delete the last column).

  col_to_delete = 'b' arr = [["a","b","c"],[2,3,5],[3,6,8],[1,3,1]] arr.transpose.collect{|a| a if (a[0] != col_to_delete)}.reject(&:nil?).transpose => [["a", "c"], [2, 5], [3, 8], [1, 1]] 
0
source

Source: https://habr.com/ru/post/1482028/


All Articles