2014-03-26 2 views
0

가 주어 동일한 속성을 가지고 배열 개체 집합 찾기 내가 객체 배열을 좀하고 싶습니다 은 내가 두 개의 속성을 가진 배열을 가지고

my_arr = [{n_parents: 10, class: 'right'}, {n_parents: 10, class: 'right'}, {n_parents: 5, class: 'left'}, {n_parents: 2, class: 'center'}, {n_parents: 2, class: 'center'}, {n_parents: 2, class: 'center'}] 

그 이 두 속성의 대부분을 공유합니다. 앞의 예에서 그래서 :

result = [{n_parents: 2, class: 'center'}, {n_parents: 2, class: 'center'}, {n_parents: 2, class: 'center'}] 

n_parents = 2class = 'center'를 공유하는 세 개의 개체가 있기 때문에.

지금까지 두 가지 속성을 두 개의 그룹으로 그룹화 할 수 있지만 이후에는 더 많은 요소가있는 세트를 가져 오는 방법을 알 수 없습니다.

는 지금은이 : 이것은 당신을 위해 일한다

my_arr.group_by { |x| [x[:n_parents], x[:class]] } 

답변

2

. 이 그룹을 해시 자체 해시 다음

my_arr = [{n_parents: 10, class: 'right'}, {n_parents: 10, class: 'right'}, {n_parents: 5, class: 'left'}, {n_parents: 2, class: 'center'}, {n_parents: 2, class: 'center'}, {n_parents: 2, class: 'center'}] 
my_arr.group_by { |h| h }.max_by { |h,v| v.count }.last 
#=>[{:n_parents=>2, :class=>"center"}, {:n_parents=>2, :class=>"center"}, {:n_parents=>2, :class=>"center"}] 
+0

당신 마일 끝에서 ssed'# last'. 그래서 방법을 생각하지 않고 어떻게 출력을 얻었는지;) –

+1

@ArupRakshit 나는 공간을 추가해야하는 이유를 알아 차 렸습니다. 명쾌함? – engineersmnky

+0

루비 애호가가 그렇게 쓰는 것처럼. [here] (http://ruby-doc.org/core-2.1.0/Enumerable.html#method-i-group_by)를 참조하십시오 .. –

0

뭔가 아래와 같이 계산 배열에 의해 가장 큰 그룹을 가져옵니다

my_arr.group_by(&:values).max_by { |_,v| v.size }.last 
# => [{:n_parents=>2, :class=>"center"}, 
#  {:n_parents=>2, :class=>"center"}, 
#  {:n_parents=>2, :class=>"center"}] 
0

내가 OP에서 사용하는 코드를 사용하고 그 결과를 얻을 이상 확장하고 그는 원 -

my_arr.group_by { |x| [x[:n_parents], x[:class]] }.max_by{|k,v| v.size}.last 

출력

#=> [{:n_parents=>2, :class=>"center"}, {:n_parents=>2, :class=>"center"}, {:n_parents=>2, :class=>"center"}] 
0

게시 할 네 번째 답변입니다. 이전의 3 가지 대답은 모두 group_by/max_by/last입니다. 물론, 이것이 최선의 방법 일 수 있지만, 가장 흥미롭고 가장 재미 있습니까? 원하는 결과를 생성하는 몇 가지 다른 방법이 있습니다.

my_arr = [{n_parents: 10, class: 'right' }, {n_parents: 10, class: 'right' }, 
      {n_parents: 5, class: 'left' }, {n_parents: 2, class: 'center'}, 
      {n_parents: 2, class: 'center'}, {n_parents: 2, class: 'center'}] 

원하는 결과 인 경우 :

#=> [{:n_parents=>2, :class=>"center"}, 
    # {:n_parents=>2, :class=>"center"}, 
    # {:n_parents=>2, :class=>"center"}] 

# 1

# Create a hash `g` whose keys are the elements of `my_arr` (hashes) 
# and whose values are counts for the elements of `my_arr`. 
# `max_by` the values (counts) and construct the array. 

el, nbr = my_arr.each_with_object({}) { |h,g| g[h] = (g[h] ||= 0) + 1 } 
       .max_by { |_,v| v } 
arr = [el]*nbr 

# 2

# Sequentially delete the elements equal to the first element of `arr`, 
# each time calculating the number of elements deleted, by determining 
# `arr.size` before and after the deletion. Compare that number with the 
# largest number deleted so far to find the element with the maximum 
# number of instances in `arr`, then construct the array. 

arr = my_arr.map(&:dup) 
most_plentiful = { nbr_copies: 0, element: [] } 
until arr.empty? do 
    sz = arr.size 
    element = arr.delete(arr.first) 
    if sz - arr.size > most_plentiful[:nbr_copies] 
    most_plentiful = { nbr_copies: sz - arr.size, element: element } 
    end 
end 
arr = [most_plentiful[:element]]* most_plentiful[:nbr_copies] 
+0

네 코드가 확실히 작동하고 흥미로운 접근이지만 동시에 다른 답변의 간결함과 가독성이 부족하므로 리팩터링 될 것입니다. – engineersmnky

+0

@ engineersmnky, 나는 100 % 동의합니다. 이것이 실생활이라면 다른 사람들처럼 group_by/max_by를 사용할 것입니다.그러나 Ruby에 관해 많은 것을 배웠습니다. 특히 때와 같이 파티에 늦었을 때 SO 질문에 대한 해결책을 생각해 보려고합니다. 나는 그들이 약간의 교육적 가치를 가질 수 있기를 희망하면서 이러한 소리들을 게시합니다. 시도 해봐! –

관련 문제