0

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.

9
  • 3
    JavaScript doesn't have associative arrays. You're misusing the JS Array type. Commented Apr 24, 2018 at 16:59
  • 2
    cm is 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 using cm = {} Commented Apr 24, 2018 at 16:59
  • 2
    Seems that you want your code reviewed and improved, but you haven't given qualifications for what counts as "nice" or "better" code. Commented Apr 24, 2018 at 17:00
  • You're right, but the upper part (the 'assoc' array) is given (dont ask why) the hole array is handled like an object. delete works! Commented Apr 24, 2018 at 17:07
  • @Sebastian yes, delete would work. Just because you can do something doesn't mean you should. Commented Apr 24, 2018 at 17:13

4 Answers 4

2

You have an object, so you can just do:

if (cm[searchKey].length===0)
{
    delete cm[searchKey]
}
Sign up to request clarification or add additional context in comments.

Comments

1

You might need Map. I think Map does a better job that you actually ask for.

Comments

1

This is a perfect usecase for a Map:

  class Multimap extends Map {
    get(key) {
      return super.get(key) || [];
    }

    addTo(key, value) {
      if(this.has(key)) {
         this.get(key).push(value);
       } else {
         this.set(key, [value]);
       }
    }

    removeFrom(key, value) {
      this.set(key, this.get(key).filter(el => el !== value));
    }
}

This can be used as:

 const cm = new Multimap([
  ["a", ["a", "b", "c"]]
 ]);

 cm.removeFrom("a", "b");
 cm.get("a").includes("b") // false

Comments

0

I used .filter on the array like so

// Remove emptys
modeSummary = modeSummary.filter(ms => ms);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.