0

I have the following array of objects:

[{key: "test", values: [{key: "2015-05", values: [{1:2}, {3:4}]}, {}], ...]

I want to filter by the key value to only be left with values after a certain date.

I currently have this, but the resulting the structure is wrong

_.map(temp1, function(value, key) { return _.filter(value.values, function(v) { return v.key > "2015-05"; }); });

1
  • 2
    "I am using _.map and _.filter but currently stuck." If you show us what you've tried (particularly the _.filter one), we can help you understand what's wrong with what you've done. Commented Mar 28, 2017 at 12:20

2 Answers 2

1

Slight improvement on Frank's answer:

var data = [
  {
    key: "1", 
    values: [
      {key: "2014-05", values: [{1:2}, {3:4}]},
      {key: "2015-05", values: [{1:2}, {3:4}]},
      {key: "2013-05", values: [{1:2}, {3:4}]}
    ]
  },
  {
    key: "2", 
    values: [
      {key: "2014-05", values: [{1:2}, {3:4}]},
      {key: "2015-05", values: [{1:2}, {3:4}]},
      {key: "2013-05", values: [{1:2}, {3:4}]}
    ]
  }
];

var a = _.map(data, (d) => {
  d.values = _.filter(d.values, (v) => v.key > "2014");
  return d;
});
console.log(a);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>

No need to parse this date format, a string comparison will suffice. Important to note, despite the _.map operation, this will modify the original.

Sign up to request clarification or add additional context in comments.

Comments

0

Something like this maybe?

var data = [
  {
    key: "1", 
    values: [
      {key: "2014-05", values: [{1:2}, {3:4}]},
      {key: "2015-05", values: [{1:2}, {3:4}]},
      {key: "2013-05", values: [{1:2}, {3:4}]}
    ]
  },
  {
    key: "2", 
    values: [
      {key: "2014-05", values: [{1:2}, {3:4}]},
      {key: "2015-05", values: [{1:2}, {3:4}]},
      {key: "2013-05", values: [{1:2}, {3:4}]}
    ]
  }
];

var a = _.map(data, (d) => {
  d.values = _.filter(d.values, (v) => {
    return Date.parse(v.key) > Date.parse("2014");
  });
  return d;
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.