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 ?

1

1 Answer 1

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

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

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.