3

I'm using Flot JS charts. I'm trying to remove one of the plot series from my data array completely with jquery or plain javascript.

This is what my data array looks like:

[
 {
  "label" : "Citrix PV Ethernet Adapter",
  "data": [[1,0], [2,0.01], [3,0.02], [4,0.01], [5,0.01]]
 },
 {
  "label" : "Virtual Adapter _1",
  "data" : [[1,0], [2,0], [3,0], [4,0], [5,0]]
 }
]

I want to be able to have the ability to completely remove one of the entries, preferably by using the "label" properties value, so it looks like this:

[
 {
  "label" : "Citrix PV Ethernet Adapter",
  "data": [[1,0], [2,0.01], [3,0.02], [4,0.01], [5,0.01]]
 }
]

Is this possible? I know it's possible to "toggle" the visibility of the series in Flot, but this doesn't suit in this case.

There could be many many entries in this array, I've just kept it to two for an example.

I've tried the playing around with javascripts delete function but I've had no luck so far.

How can this be done?

Alex
  • 1,549
  • 2
  • 16
  • 41
  • `delete` is an operator not a function, what you need is `slice` or `splice`. – elclanrs Mar 21 '14 at 07:15
  • @elclanrs I managed to accomplish this using `delete` on a simpler array like this: `delete simpleArray["key1"];`, but I can't work out how to do it on the array I posted above - I'll investigate `slice` and `splice`. – Alex Mar 21 '14 at 07:17
  • 2
    You mean on a simpler **object**? Arrays have their own methods for deleting elements https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice – elclanrs Mar 21 '14 at 07:18
  • @elclanrs Yes I guess an object then. The example in that case was `var simpleArray = {"key1":true}`, so I see why it will work only in that case. – Alex Mar 21 '14 at 07:20

1 Answers1

3

Assuming you know the index of the element you want to remove, you can then use splice() to remove it.

So given:

var chartDataArray = [
 {
  "label" : "Citrix PV Ethernet Adapter",
  "data": [[1,0], [2,0.01], [3,0.02], [4,0.01], [5,0.01]]
 },
 {
  "label" : "Virtual Adapter _1",
  "data" : [[1,0], [2,0], [3,0], [4,0], [5,0]]
 },
 {
  "label" : "Citrix PV Ethernet Adapter 2",
  "data": [[3,0.02], [4,0.01], [5,0.01]]
 },
 {
  "label" : "Virtual Adapter _3",
  "data" : [[1,0], [2,0], [3,0]]
 }
]

Then following will remove the item at index 2:

chartDataArray.splice(2, 1);
Matt Tester
  • 4,663
  • 4
  • 29
  • 32
  • Thanks, I'll try and work with this. I assume there is no **easy** way to do it using the "label" value? – Alex Mar 21 '14 at 07:25
  • 1
    Take a look at this question on how to find the object in the array: http://stackoverflow.com/questions/15997879/get-the-index-of-the-object-inside-an-array-matching-a-condition – Matt Tester Mar 21 '14 at 07:29