简体   繁体   中英

Sum and sort with Ramda.js

I have an object which has object of array of numbers like so:

books = [{
  id: "a6113b1cd5d4617f63bb10abc874bea7",
  times: [{
    0: 1,
    1: 5
  }],
  length: 1,
  rating: 4.77,
}, {
  id: "b6113b1cd5d4617f63bb10abc874bea7",
  times: [{
    0: 8
  }],
  length: 1,
  rating: 2.6,
}]

I want to add sort by times , but that needs to be sum of all elements inside that object - In the example for the first object it is 1+5=6 and for the second object is 8 so the sorted end result is first object then second. This is what I have so far but it's incomplete. Do you have idea how do i get the sum of the array?

const timesSorting =  R.ascend(R.path(['times']))
const sorting = R.sortWith([timesSorting])
sorting(books)

Use R.sortBy because you need to sort by a single property. Create a function that gets the time prop, use R.chain with R.values to get an array of all values in the time array, and sum them.

 const { pipe, prop, chain, values, sum, sortBy} = R const getTimesSum = pipe(prop('times'), chain(values), sum); const sorting = sortBy(getTimesSum) const books = [{"id":"a6113b1cd5d4617f63bb10abc874bea7","times":[{"0":1,"1":5}],"length":1,"rating":4.77},{"id":"b6113b1cd5d4617f63bb10abc874bea7","times":[{"0":8}],"length":1,"rating":2.6}] const result = sorting(books) console.log(result)
 <script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.27.1/ramda.min.js" integrity="sha512-rZHvUXcc1zWKsxm7rJ8lVQuIr1oOmm7cShlvpV0gWf0RvbcJN6x96al/Rp2L2BI4a4ZkT2/YfVe/8YvB2UHzQw==" crossorigin="anonymous"></script>

If times is always an array with a single object that has numerical indexes, you can simplify times to an array of numbers, and then it would be easier to sum:

 const { pipe, prop, sum, sortBy } = R const getTimesSum = pipe(prop('times'), sum); const sorting = sortBy(getTimesSum) const books = [{ "id": "a6113b1cd5d4617f63bb10abc874bea7", "times": [1, 5], // an array of numbers "length": 1, "rating": 4.77 }, { "id": "b6113b1cd5d4617f63bb10abc874bea7", "times": [8], // an array of numbers "length": 1, "rating": 2.6 }] const result = sorting(books) console.log(result)
 <script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.27.1/ramda.min.js" integrity="sha512-rZHvUXcc1zWKsxm7rJ8lVQuIr1oOmm7cShlvpV0gWf0RvbcJN6x96al/Rp2L2BI4a4ZkT2/YfVe/8YvB2UHzQw==" crossorigin="anonymous"></script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM