Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I make array using split

    function category_array() {
        var send_array = Array();
        var send_cnt = 0;
        var chkbox = $('input[name="category[]"]:checked');

        for(i=0;i<chkbox.length;i++) {
                if (chkbox[i].checked == true){
                        send_array[send_cnt] = chkbox[i].value;
                        send_cnt++;
                }
        }

        console.log(send_array);
        $("#category_list").val(send_array);
    }

now result is [‘men_a’, ‘men_b’, ‘mem_c’, ‘woman_a’, ‘woman_d’]

What I want {men: [a,b,c], women: [a,d]}

How to do ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

loop over arr, and get gendre and its value and add them to the first res variable if gendre is male else to second.

const arr = ["men_a", "men_b", "mem_c", "woman_a", "woman_d"];
const res = [[], []];
for (person of arr) {
  const [gendre, value] = person.split("_");
  if (gendre == "men") res[0].push(value);
  else res[1].push(value);
}
console.log(JSON.stringify(res)); // [["a","b"],["c","a","d"]]

Update to store values in an object instead of an array

const arr = ["men_a", "men_b", "mem_c", "woman_a", "woman_d"];
const res = {'men':[],'women':[]};
for (person of arr) {
  const [gendre, value] = person.split("_");
  if (gendre == "men") res['men'].push(value);
  else res['women'].push(value);
}

console.log(JSON.stringify(res)); // {"men":["a","b"],"women":["c","a","d"]}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading