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 ?
>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"]}