0

I have an array of Plotly traces.

console.log(traces):

traces:
[{…}]
0:
name: "temprature"
type: "scatter"
x: (7523) [1527581340000, …]
y: (7660) [15.68, …]
__proto__: Object
length: 1
__proto__: Array(0)

At an event, I want to check if a newly created trace is on the list or not. Firstly, I check it with the includes function but it didn't work, then I found this answer on how to check the availability of an object in an array in js.

function contains(a, obj) {
        for (var i = 0; i < a.length; i++) {
            if (a[i] === obj) {
                return true;
            }
        }
        return false;
}

but it seems not to work for me.

$("#temprature").change(function () {
        var trace_temprature  = {
                            x: index,
                            y: temprature,
                            name: document.getElementById('temprature').name,
                            type: 'scatter'
        };

        if (document.getElementById('temprature').checked) {
            if( !traces.includes(trace_temprature) ){
                traces.push(trace_temprature);
            }
            console.log('trace in the add ', traces);           
            console.log('temperature trace: ', trace_temprature) // this line prints the same object on the previous list
            
        } else {
            console.log('if condiiton: ', contains(traces, trace_temprature)); // this line print False
            if( contains(traces, trace_temprature) ){
                var ind = traces.indexOf(trace_temprature);
                traces.splice(ind, 1);
            }

        }
      
    });

any ideas?

Shahriar.M
  • 818
  • 1
  • 11
  • 24
  • @pilchard do you mean I should implement an `isEqual` function for plotly trace type? – Shahriar.M Dec 16 '20 at 10:14
  • I mean you can't evaluate object equality by a simple `===` comparison so `a[i] === obj` fails (unless they are references to the same object). So you need to implement some form of equality checking (by a single property, by a combination or properties, by all properties...up to you) for the `contains` function to return meaningful information. Also look at [`some()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some). – pilchard Dec 16 '20 at 10:20

0 Answers0