简体   繁体   English

jQuery将值添加到数组(如果不存在)

[英]Jquery add value to an array if does not exist

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 . 我想将返回的值添加到类别json数组,但仅添加唯一值。 However , the checking of the value in the array does not return a true at all. 但是,检查数组中的值根本不会返回true。 Which condition should I use to check if the value exists in the array ? 我应使用哪种条件检查数组中是否存在该值?

You push the element to the array in another array 您将元素推到另一个数组中的数组

your code category_json.push([data[i].group_name]); 您的代码category_json.push([data[i].group_name]);

should be like this category_json.push(data[i].group_name); 应该像这个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 之后,您像这样检查arr.indexOf(3)并始终返回-1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM