0

I have the following array structure:

[   ["one_id",[["1a", 10], ["1b", 54], ["1c", 43]]], 
    ["two_id",[["2a", 32], ["2b", 76], ["2c", 34]]], 
    ["thr_id",[["3a", 85], ["3b", 13], ["3c", 42]]], 
    ["fou_id",[["4a", 15], ["4b", 21], ["4c", 65]]], 
]

And I would like to drop the "value" of the nested arrays to get to an output like:

[   ["one_id",  ["1a","1b","1c"]], 
    ["two_id",  ["2a","2b","2c"]], 
    ["thr_id",  ["3a","3b","3c"]], 
    ["fou_id",  ["4a","4b","4c"]], 
]

Any suggestion?

4 Answers 4

2

This is a non-destructive one:

array.map{|k, v| [k, v.map(&:first)]}
#=> [
  ["one_id", ["1a", "1b", "1c"]],
  ["two_id", ["2a", "2b", "2c"]],
  ["thr_id", ["3a", "3b", "3c"]],
  ["fou_id", ["4a", "4b", "4c"]]
]
Sign up to request clarification or add additional context in comments.

Comments

2

There is the code

arr = [   ["one_id",[["1a", 10], ["1b", 54], ["1c", 43]]], 
    ["two_id",[["2a", 32], ["2b", 76], ["2c", 34]]], 
    ["thr_id",[["3a", 85], ["3b", 13], ["3c", 42]]], 
    ["fou_id",[["4a", 15], ["4b", 21], ["4c", 65]]], 
]

arr2 = arr.map do |element|
    r = [element[0]]
    r << element[1].map(&:first)
    r
end

Comments

1

If by "drop the 'value'" you meant "replace innermost array to its first element:

Warning: this code contains magic number and is not even general.

require "pp"

a = [   ["one_id",[["1a", 10], ["1b", 54], ["1c", 43]]],
        ["two_id",[["2a", 32], ["2b", 76], ["2c", 34]]],
        ["thr_id",[["3a", 85], ["3b", 13], ["3c", 42]]],
        ["fou_id",[["4a", 15], ["4b", 21], ["4c", 65]]],
]

a.each do |lv1|
  lv1[1].map! &:first
end

pp a

# => 
# [["one_id", ["1a", "1b", "1c"]],
# ["two_id", ["2a", "2b", "2c"]],
# ["thr_id", ["3a", "3b", "3c"]],
# ["fou_id", ["4a", "4b", "4c"]]]

Comments

0
    require "pp"

    array = [   ["one_id",[["1a", 10], ["1b", 54], ["1c", 43]]],
            ["two_id",[["2a", 32], ["2b", 76], ["2c", 34]]],
            ["thr_id",[["3a", 85], ["3b", 13], ["3c", 42]]],
            ["fou_id",[["4a", 15], ["4b", 21], ["4c", 65]]],
    ]

    array.collect{|k, v| [k, v.collect(&:first)]}

# [["one_id", ["1a", "1b", "1c"]], 
#  ["two_id", ["2a", "2b", "2c"]], 
#  ["thr_id", ["3a", "3b", "3c"]], 
#  ["fou_id", ["4a", "4b", "4c"]]]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.