I have an assoc js array and i want to remove one element from it. My solution works but it is not really nice, is there a better solution?
// i got this assoc array
var cm = [];
cm["a"] = ["a"];
cm["b"] = ["c"];
cm["s"] = ["a", "b", "c"];
cm["x"] = [];
console.log(cm);
var searchKey = "s";
var p = ["a","c","d", "b"]; // to remove from searchKey array
// remove elements (works fine)
cm[searchKey] = cm[searchKey].filter(value => (p.includes(value) === false));
console.log(cm); // now cm[searchKey] is an empty array
// if the array at index 'searchKey' is empty remove it from assoc array
var newarray = [];
if (cm[searchKey].length===0)
{
for(key in cm)
{
if (key!=searchKey) newarray[key] = cm[key];
}
}
cm = newarray;
console.log(cm);
I tried with filter and splice, but both works only at arrays not assoc array.
cmis not an associative array. You shouldn't be doing that - you are actually making an array but then just treating it as an object by setting properties on it. You should be instantiating an object instead by usingcm = {}deletewould work. Just because you can do something doesn't mean you should.