Reputation: 1272
I need to write:
function remove(str, what)
that takes in a string str and an object what and returns a string with the chars removed in what. For example:
remove('this is a string',{'t':1, 'i':2}) ====> 'hs s a string'
remove from 'this is a string' the first 1 't' and the first 2 i's.
======================================================================
I'm stuck on how to access just the letter or just the number from the what object. There isn't a name, just a set of values. Do I have to somehow define it first? Maybe something like this:
var a;
var b;
var what = {letter: a, number:b}
and then use dot notation to grab each value?
what.letter
Upvotes: 0
Views: 39
Reputation: 1855
You're on the right path!
Whether or not your function is being called with a the value of an assigned variable or an object literal for an argument...
function remove(str, what) {
...
}
var what = {
e: 1
};
remove('hello', what);
// is functionally equivalent to
remove('hello', {
e: 1
});
... your function will still have an object passed in as one of its arguments which you can then access through dot or bracket notation.
From there you'll want to iterate over the keys of your object, possibly using Object.keys
or a for ... in
loop, to extract the values for performing manipulation on your string.
Upvotes: 0
Reputation: 198324
Object.keys
gets you the array of all the keys from the object (i.e. ['a', 't']
in your example). Then you just iterate over that and access the corresponding count.
function remove(str, what) {
Object.keys(what).forEach(function(letter) {
var count = what[letter];
// ...
});
}
Upvotes: 1