Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove one level of a nested array

Tags:

arrays

ruby

How can you change this array:

[["1","one"], ["2","two"], ["3","three"]]

to this?

["1","one"], ["2","two"], ["3","three"]

Clarification

My apologies for giving an invalid second version. This is what I'm really going for:

I want to add ["0","zero"] to the beginning of [["1","one"], ["2","two"], ["3","three"]], to get:

[["0","zero"], ["1","one"], ["2","two"], ["3","three"]]

I have tried:

["0","zero"] << [["1","one"], ["2","two"], ["3","three"]]

The above approach produces this, which contains a nesting I don't want:

[["0","zero"], [["1","one"], ["2","two"], ["3","three"]]]
like image 368
sscirrus Avatar asked May 19 '11 23:05

sscirrus


People also ask

How do I get rid of nested arrays?

To remove elements from any sub-arrays of a nested array, use the “pop()” method. The “pop()” method typically deletes the last inner-array from a nested array; however, it also helps in removing elements from inner arrays.

What is Flattening an array?

Flattening an array is a process of reducing the dimensionality of an array. In other words, it a process of reducing the number of dimensions of an array to a lower number.

How do you remove the middle element from an array?

You can remove elements from the end of an array using pop, from the beginning using shift, or from the middle using splice. The JavaScript Array filter method to create a new array with desired items, a more advanced way to remove unwanted elements.


1 Answers

unshift ought to do it for you:

a = [["1","one"], ["2","two"], ["3","three"]]
a.unshift(["0", "zero"])
=> [["0", "zero"], ["1", "one"], ["2", "two"], ["3", "three"]]
like image 128
Wayne Conrad Avatar answered Oct 09 '22 17:10

Wayne Conrad