Home > Back-end >  How can i transcript from js to ruby these functions: sort, find and Set
How can i transcript from js to ruby these functions: sort, find and Set

Time:11-25

I want to sort by 'type', in my example there is several objects depends of type'A', 'B', 'C' and so on

Also i am using find to verify if V1 is higher than V2

And also i want to sort by V1 field, this is my code in js, but now i would like to pass to Ruby on rails

Btw: my code is working so far

const sections = [{
  "type": "A",
  "v1": 1002,
  "v2": 1001
}, {
  "type": "A",
  "v1": 1700,
  "v2": 1900
}, {
  "type": "A",
  "v1": 1100,
  "v2": 1200
}, {
  "type": "B",
  "v1": 1000,
  "v2": 1700
}]

var sections_b = _.groupBy(sections, (n) => n.type);
const withoutRepetitions = [...new Set(sections.map(e => e.type))]

for (w of withoutRepetitions) {
  c = sections_b[w]
  const isOk = c.find((ele) => ele['v1'] >= ele['v2'])
  let sortedArray = c.sort((a, b) => a['v1'] - b['v1'])
  console.log('sortedArray', sortedArray)
}
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>

CodePudding user response:

Couldn't find out what your isOK variable is for, but here is a ruby snippet which does the same:

sections = [{
  "type": "A",
  "v1": 1002,
  "v2": 1001
}, {
  "type": "A",
  "v1": 1700,
  "v2": 1900
}, {
  "type": "A",
  "v1": 1100,
  "v2": 1200
}, {
  "type": "B",
  "v1": 1000,
  "v2": 1700
}]

sections_b = sections.group_by{ |s| s[:type] }

sections_b.each do |key, secs|
    isOK = secs.find{ |s| s[:v1] >= s[:v2] }
    sortedArray = secs.sort_by{ |s| s[:v1] }
    puts sortedArray
end
  • Related