If you want to merge, sometimes you need to splice as well. Try this :
var countryArray = [{
"country" : "Indonesia",
"state" : ["DKI","Bali"],
},
{
"country" : "Malaysia",
"state" : ["Penang","Johor"],
}];
To merge with incoming new data ;
var newArr = [{ "country" : "Malaysia", "state" : ["Kelantan"] }];
MergeArray(countryArray,newArr);
console.table(countryArray);
To Splice form the incoming data ;
var DelArray = [{ "country" : "Malaysia", "state" : ["Penang"] }];
SpliceArray(countryArray,DelArray);
console.table(countryArray);
and the related function ;
function MergeArray(countryArray,newArr) {
var a = 0;
$.each(newArr, function (key, data1) {
var b = 0;
$.each(countryArray, function (key, data2) {
if(data1.country == data2.country) { // match the same country
countryArray[b]["state"] = countryArray[b]["state"].concat(newArr[a]["state"]);
}
b++; });
a++; });
}
function SpliceArray(countryArray,DelArray) {
var a=0;
$.each(DelArray, function (key, data1) {
var b=0;
$.each(countryArray, function (key, data2) {
if(data1.country == data2.country) { // get same country
console.log(countryArray[b]["state"]) // ["Penang", "Johor", "Kelantan"]
for(var c=0; c < countryArray[b]["state"].length; c++){ // loop in countryArray state[]
console.log(DelArray[a]['state']); // to remove : ["Penang"]
if(countryArray[b]["state"][c] == DelArray[a]['state'] ) {
countryArray[b]["state"].splice(c,1); // remove ["Penang"]
}
}
}
b++;
});
a++;
});
}
hope will help