omygoodness
omygoodness

Reputation: 365

Ramda - How to sort array with nested object with string to number conversion

I am trying to sort the array which looks like this:

const testArray = [
  {
    "id": "1",
    "nodeLayout": {
      "x": "12.0",
      "y": "1.0",
      "width": 200,
      "height": 87
    }
  },
  {
    "id": "2",
    "nodeLayout": {
      "x": "1.0",
      "y": "1.0",
      "width": 200,
      "height": 87
    }
  },
  {
    "id": "3",
    "nodeLayout": {
      "x": "0.0",
      "y": "1.0",
      "width": 200,
      "height": 87
    }
  }
]

I was trying to sort it with this:

R.pipe(
  R.pluck('nodeLayout'),
  R.map(R.pipe(R.props(['x']), R.join(','))),
  R.sortWith([R.ascend(parseFloat)])
)(testArray)

Which is working fine but I am getting only x values sorted and I am not able to fit this sort into this one:

R.pipe(
  R.filter(
    R.allPass([
      R.pathEq(['nodeLayout', 'y'], '1.0'),
      R.propEq('group', 4)
    ]
  ))
  // I tried to add it here: R.sortBy(R.path(['nodeLayout', 'x'])) but I need to parse string first and I have no idea how to combine those
)(testArray)

To sum up, I am trying to get the whole object with all properties sorted.

Any help would be appreciated. Thank you

Upvotes: 1

Views: 238

Answers (1)

Scott Christopher
Scott Christopher

Reputation: 6516

If you combine your two approaches, you should be able to achieve what you're wanting.

The main thing being that you can R.pipe the call to parseFloat after obtaining the value you'd like to sort with R.path. This piped function can be provided as the argument to R.sortBy.

R.pipe(
  R.filter(
    R.allPass([
      R.pathEq(['nodeLayout', 'y'], '1.0'),
      R.propEq('group', 4)
    ]
  )),
  R.sortBy(R.pipe(R.path(['nodeLayout', 'x']), parseFloat))
)(testArray)

Upvotes: 2

Related Questions