+1 vote
by (550 points)

Achieving this would vastly simplify my writing template, but again my JS is too limited. Sorry if the question is too complex (or too easy!).

Let's say I have an object with arrays as values, like this:

s.a.aa = ["red", "blue", "green"]
s.a.bb = ["white", "black", "YES"]
s.a.cc = ...

What I need to do is removing "YES" from s.a. But I don't know where it is. It is somewhere within the arrays that populate s.a, but I don't know in which specific key I must search. (Note: all values are unique, as in the examnple.)

So, how would you go about it? Is there a simple way?

I've tried the most logical solution to this (keeping track of where the thing is when I need it) but I've failed with error messages that I can't even begin to understand.

Thanks!

1 Answer

+1 vote
by (2.5k points)
selected by
 
Best answer

This should work on IE 9 and later-- which covers most audiences, but wanted to note it. It will also remove all instances of the string YES.

Object.keys(s.a).forEach(function(key) {
  s.a[key] = s.a[key].filter(function(contents) {
    return contents !== 'YES';
  });
});

 

by (550 points)

Thank you! It was obvious it wasn't going to be so complex. Instead of checking every array and removing the value from the array containing it, it simply performs the removal value on all the arrays, doesn't it? I never thought of that.

One more question, that may be related to the reason my other attempt failed. If I do this:

window.customRemove = function(value) {
  Object.keys(s.a).forEach(function(key) {
    s.a[key] = s.a[key].filter(function(contents) {
      return contents !== value;
    });
  });
}

And call it from another point, on click after printing a passage, I get this:

ReferenceError: s is not defined

And I have absolutely zero idea what may be happening.

Thanks again!

...