How to "Unflatten" a Ruby Array

How to unflatten a Ruby Array?

The shortest and fastest solution is using Array#zip:

values = [5, 7, 8, 1]
values.zip # => [[5], [7], [8], [1]]

Another cute way is using transpose:

[values].transpose # =>  [[5], [7], [8], [1]]

The most intuitive way is probably what @Thom suggests:

values.map { |e| [e] }

Using flatten! on an array of arrays not working

the flatten is working perfectly. the issue you are having is that you have lots of strings in your output, with commas in them.

having not got a copy of your CSV, I'm going to assume that it has been parsed correctly, and that you do want to keep the contents of the first cell as it is:

def parse_therapies(therapy_array) 
parsed_therapy_array = therapy_array.map { |x| x && x.split(/,/) }.flatten.compact
therapy_array.replace(parsed_therapy_array)
end

this will also remove all the nil elements, assuming you don't want them, using the compact procedure.

create subarray from sequence


arr.slice_before(&:nil?).map(&:compact).reject(&:empty?)

Just out of curiosity, O(N):

arr.inject([[]]) do |memo, e| 
e ? memo.last << e : (memo << [] unless memo.last.empty?)
memo
end

Or, with modern ruby goodness:

arr.each_with_object([[]]) do |e, memo| 
e && memo.last << e || (memo << [] unless memo.last.empty?)
end

And, totally out of curiosity (it’s a joke, please, do not use):

JSON.parse arr.to_json
.gsub(/\D{2,}/, '],[')
.gsub(/\A\D+/, '[[')
.gsub(/\D+\z/, ']]')

How to reshape a flattened array to a multidimensional array in arbitray shape in Javascript?

Here's my solution:






const A = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
const C = [3, 4];

function unflattenArray(arr, dim) {
let elemIndex = 0;

if (!dim || !arr) return [];

function _nest(dimIndex) {
let result = [];

if (dimIndex === dim.length - 1) {
result = result.concat(arr.slice(elemIndex, elemIndex + dim[dimIndex]));
elemIndex += dim[dimIndex];
} else {
for (let i = 0; i < dim[dimIndex]; i++) {
result.push(_nest(dimIndex + 1));
}
}

return result;
}
return _nest(0);
}

console.log(unflattenArray(A, C));

Wrong number of arguments' error in RUBY

Given your operator

  def [](x, y)
@data[x][y]
end

Your map's elements should be accessed via map[i,j] instead of map[i][j].

Sort Ruby array by a set of parameters, fall back to next parameter in case it's undefined

Not sure if this is what you are after, but a quick solution could be:

arr = [{a:"never", b:"anna"}, {a:"always", b:"bob"}, {b:"colin"}, {b:"abe"}]
arr.sort_by! {|o| o[:a] ? o[:a] : o[:b] }
#=> [{:b=>"abe"}, {:a=>"always", :b=>"bob"}, {:b=>"colin"}, {:a=>"never", :b=>"anna"}]

Find a Duplicate in an array Ruby

Array#difference comes to the rescue yet again. (I confess that @user123's answer is more straightforward, unless you pretend that Array#difference is already a built-in method. Array#difference is probably the more efficient of the two, as it avoids the repeated invocations of count.) See my answer here for a description of the method and links to its use.
In a nutshell, it differs from Array#- as illustrated in the following example:

a = [1,2,3,4,3,2,4,2]
b = [2,3,4,4,4]

a - b #=> [1]
a.difference b #=> [1, 3, 2, 2]

One day I'd like to see it as a built-in.

For the present problem, if:

arr = [1,2,3,4,3,4]

the duplicate elements are given by:

arr.difference(arr.uniq).uniq
#=> [3, 4]

how to sort array in ruby if i have nil object inside array?

Handle the nil, this will get you close...

2.1.2 :010 > my_array.sort { |x,y| x && y ? (x <=> y) : (x ? -1 : 1) }
=> ["12", "12 months", "13 months", nil, nil]

It's not exact, '12' comes before the rest based on the <=> comparison. If you want more control you'll need to have a more complex comparison block.



Related Topics



Leave a reply



Submit