Rakesh Patidar
Rakesh Patidar

Reputation: 196

Select items from arrays of an array with certain indexes

I want to select items from each array of arr from index position 0, 2 and 4

Input array

arr = [
  ["name", "address", "contact", "company", "state"],
  ["n1", "add1", "c1", "cp1", "s1"],
  ["n2", "add2", "c2", "cp2", "s2"] 
]

Output array

arr = [
  ["name", "contact", "company"],
  ["n1", "c1", "cp1"],
  ["n2", "c2", "cp2"]
]

Upvotes: 2

Views: 3752

Answers (5)

peter
peter

Reputation: 42207

If you want tot take this more generic and only select the even columns you could do it like this

arr.map{|a| a.select.with_index { |e, i| i.even? }}

which gives

[["name", "contact", "state"], ["n1", "c1", "s1"], ["n2", "c2", "s2"]]

Upvotes: 5

maicher
maicher

Reputation: 2745

It can be also performed with each_slice method.

If 0, 2, 4 values can be treated as a list with every second value omitted (_), it can be written like:

arr.map { |a| a.each_slice(2).map { |item, _| item } }

Upvotes: 1

sheepdog
sheepdog

Reputation: 625

Ruby has very nice destructuring syntax, so you can extract all your values in a one-liner:

a = 0.upto(5).to_a # => [0, 1, 2, 3, 4, 5]
x, _, y, _, z = a

x # => 0
y # => 2
z # => 4

The underscores are just placeholder for values you don't need.

Upvotes: 1

shivam
shivam

Reputation: 16506

Original question:

I want to delete items from each array of arr from index position 1 and 5

We can use delete_if to achieve this. Here:

arr.map { |a| a.delete_if.with_index { |el, index| [1,5].include? index } }
# => [["name", "contact", "company", "state"], ["n1", "c1", "cp1", "s1"], ["n2", "c2", "cp2", "s2"]]

PS: the output in question is incorrect as for arrays at index 1 and 2, example is deleting element at index 4

Upvotes: 1

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230531

as an alternative to deleting unneeded items, you can just select the needed items.

arr.map{|subarray| subarray.values_at(0, 2, 4) }
# => [["name", "contact", "state"], ["n1", "c1", "s1"], ["n2", "c2", "s2"]]

Upvotes: 6

Related Questions