MrPizzaFace
MrPizzaFace

Reputation: 8086

How to remove outer array from a nested array?

If I have the following arr = [13,12,31,31] Now say I want to push in another set of numbers like 12,13,54,32

So I can do arr << [12,13,54,32] but now I have [13,12,31,31,[12,13,54,32]]

So how can I remove the outside array? arr = arr.pop works sometimes but I'm guessing that a better way exists. Please enlighten.

Upvotes: 5

Views: 3669

Answers (3)

Marc Baumbach
Marc Baumbach

Reputation: 10473

You have a couple options. You could join your arrays using the + operator and not have to deal with the outer array. If you have an outer array and want to flatten it, simply call flatten on the array. As matt mentioned in the comments above, you can also use concat.

# Creates a new array
[13,12,31,31] + [12,13,54,32]
=> [13, 12, 31, 31, 12, 13, 54, 32]

# Creates a new array, unless you use flatten!
[13, 12, 31, 31, [12, 13, 54, 32]].flatten
=> [13, 12, 31, 31, 12, 13, 54, 32]

# Modifies the original array
[13,12,31,31].concat([12,13,54,32])
=> [13, 12, 31, 31, 12, 13, 54, 32]

Upvotes: 2

user229044
user229044

Reputation: 239240

Don't use <<, use +

arr = [13,12,31,31]

arr +=  [12,13,54,32]

# arr => [13,12,31,31,12,13,54,32]

Upvotes: 10

bjhaid
bjhaid

Reputation: 9752

You should use Array#flatten

[[13,12,31,31,12,13,54,32]].flatten # => [13, 12, 31, 31, 12, 13, 54, 32]

Upvotes: 8

Related Questions