0

I have the following function which supposed to add a value to an array if does not exist.

    var category_json = new Array();
                $.ajax({
                    type: 'POST',
                    url: "<?php echo base_url(); ?>Reports/appointment_distribution_by_group/",
                    dataType: 'JSON',
                    data: {county: county, sub_county: sub_county, facility: facility, date_from: date_from, date_to: date_to},
                    success: function (data) {
                        // Populate series
                        for (i = 0; i < data.length; i++) {
 /* Values returned from variable data as data[i].group_name = > Adolescents,Adolescents,All,All,ART Clients,ART Clients,ART Clients,ART Clients,Lactating woman,New Clients,New Clients,Paeds on ART,Paeds on ART,PMTCT,PMTCT */                               
                            if(jQuery.inArray(data[i].group_name,category_json)!== -1) {
                                //element exists in array
                                console.log(" Found ..." + data[i].group_name);
                            } else {
                                //element not found in array
                                category_json.push([data[i].group_name]);
                                console.log("Not Found ..."+data[i].group_name);
                                console.log(category_json);
                            }

                        }
                        var type = jQuery.type(category_json);
                        alert(category_json);
                        alert(type);
                        // draw chart

                    }, error: function (errorThrown) {

                    }});

I want to add the returned values to the category json array , but only unique values . However , the checking of the value in the array does not return a true at all. Which condition should I use to check if the value exists in the array ?

hassan
  • 7,812
  • 2
  • 25
  • 36
H Dindi
  • 1,484
  • 6
  • 39
  • 68
  • Possible duplicate of [How do I check if an array includes an object in JavaScript?](https://stackoverflow.com/questions/237104/how-do-i-check-if-an-array-includes-an-object-in-javascript) – Nadir Laskar May 28 '17 at 10:39

1 Answers1

2

You push the element to the array in another array

your code category_json.push([data[i].group_name]);

should be like this category_json.push(data[i].group_name);

Example:

var arr = [1, 2];

arr.push([3]);

console.log(arr); // [1, 2, [3]]

after that you check like this arr.indexOf(3) and this always return -1

Mohamed Abbas
  • 2,228
  • 1
  • 11
  • 19