Сергей Соколов Alex спасибо за участие и советы. Мое решение на coffescript
list = [
warehouses: [1]
,
warehouses: [2]
,
warehouses: [3]
,
warehouses: [4, 1]
,
warehouses: [5, 2]
,
warehouses: [6, 3, 2]
]
#получаем массив id магазинов отсортированный по частоте
counted = list
.reduce (acc, {warehouses}) ->
for w in warehouses
acc[w] = {warehouse: w, data: []} unless acc[w]
acc[w].data.push w
acc
, []
.sort (a, b) -> b.data.length - a.data.length
.map (i) -> i.warehouse
.filter (i) -> i > 0
_r = []
for w in counted
_r[w] = {warehouse: w, data: []} unless _r[w]
for i in list
if i.warehouses.includes w
_r[w].data.push i
delete list[i]
result = _r
.sort (a, b) -> b.data.length - a.data.length
.filter (i) -> i isnt null
console.log 'r', result