I am writing a function called "countWords".
Given a string, "countWords" returns an object where each key is a word in the given string, with its value being how many times that word appeared in th given string.
Notes:
* If given an empty string, it should return an empty object.
function countWords(str) {
var obj = {};
var split = str.split(" ");
return split;
}
var output = countWords('ask a bunch get a bunch');
console.log(output); // --> MUST RETURN {ask: 1, a: 2, bunch: 2, get: 1}
Have any idea?
I wont give you finished code ( thats not the sense of a homework) , but i try to get you to solve the problem on your own.
So far you've already got an array of words.
Next lets declare an object we can assign the properties later.
Then we'll iterate over our array and if the array element doesnt exist in our object as key yet ( if(!obj[array[i]])) well create a new property, with elements name and the value 1.( obj[array[i]=1; )
If the element is a key of that object, lets increase its value.
( obj[array[i]]++;)
Then return the object.
So you could use a javascript Map for this like so:
var myMap = new Map();
myMap.set(keyString, count);
and access the value of the key like so:
myMap.get(keyString);
For more information you can read up here https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Map
Related
I have a huge object that contains the entire ESV Bible. I am trying to get a random book of the Bible whenever I press a button. Here is a small sample of the object.
var esvObject = {
"Genesis": {
"1": {}
"2": {}
"3": {}
},
"Exodus": {
"1": {}
"2": {}
"3": {}
}
}
Here is the code that I am using to get a random book.
var randNum = Math.floor(Math.random() * 66);
var randBook = esvObject[randNum];
var output = randBook;
I would expect this to work, but the output I always get is "undefined," where as I would like the output to be "Genesis" or "Exodus" etc. Getting the random number works, but if
randNum = 1
then
randBook = esvObject[1]
the output returns as "undefined" and I don't know why.
Well the reason you get undefined is that your object is of the structure:
let esvObject = {
bookName: {
1 : {}
}
}
Using bracket [] notation on a javascript object finds the matching key for the name and returns it's value. In your top level object (the one with bookNames for keys), you have to use a valid book name like Genesis. To do so, leverage the Object.keys function of javascript to get an array of all the keys in your object.
You can then use [] notation, which has a different semantic on arrays.
let books = Object.keys(esvObject); // ["Genesis", "Exodus", ...]
let randomKey = books[randNum] // this is an array, so index access works
let book = esvObject[randomKey] // matches on the bookname
And to tie it all together, esvObject["Genesis"][1] would have been valid because the object stored as "Genesis" has a property 1
You are generating random number. And then trying to pick property using that number.
But you object has properties Genesis and Exodus not 1 or 20 etc.
What you need to do is Object.getOwnPropertyNames(esvObject)
that will give you array of the property names. In this case ['Genesis', 'Exodus'] and then you need to pick random element from that array
It would not work because it does not know that the first book is named "Genesis".
To be able to use numbers from the random function you will need to use array from the keys of the object
var keys = esvObject.keys( obj );
randBookKey = keys[randNum]
randBook = esvObject[randBookKey]
esvObject (as you show it) does not have any integer keys. So you need to select a random (existing) key instead:
esvObject[Object.keys(esvObjects)[Math.floor(Math.random() * 66)]]
You're confusing accessing an array with accessing an object.
An array:
arr = ["genesis", "exodus"]
is accessed like this:
arr[0] // genesis
An object:
obj = { "genesis" : "foo", "exodus" : "bar"}
is accessed like this:
obj["genesis"] // foo
To achieve what you want to do, see Access non-numeric Object properties by index?
Problem:
Declare a variable named myArray and assign it to an empty array.
Great! Now populate myArray with two strings.
Put your full name in the first string, and your Skype handle in the second.
Next, declare a function named cutName. It should expect a parameter name.
cutName should return an array by breaking up the input string into individual words. For example "Douglas Crockford" should be returned as ["Douglas", "Crockford"]
Declare a new variable named myInfo and assign it to an empty object literal.
Add the following three key-value pairs to myInfo:
Key: fullName
Value: The result of calling cutName on the name string within myArray.
Key: skype
Value: The Skype handle within myArray.
Key: github
Value: If you have a github handle, enter it here as a string. If not, set this to null instead.
My code
var myArray = ['Isaiah Sias', 'isaiahsias15689'];
function cutName(name){
var splitString = name.split(myArray[0]' ');
return splitString;
}
var myInfo{
fullName = cutName(myArray[0]),
skype = myArray[1],
github='#kakashihatake',
};
Once again I am not sure where I am messing up. I have been working on this problem for a few days now and find myself a little frustrated.
You are very close, you have made a small mistake in the cutName function.
The string.split method takes only 1 parameter, the string to split by. You've tried to pass in the array element as well. Get rid of it! (Keep in mind that the thing we are splitting, name, has been assigned the array element as its value during the function call)
var splitString = name.split(myArray[0]' ');
becomes
var splitString = name.split(' ');
One other issue, you'll need to change your object definition a bit. You have a missing = between myInfo and the start of the object literal. And, when setting property names and values in an object literal you need to use colon instead of equals, so your object
var myInfo{
fullName = cutName(myArray[0]),
skype = myArray[1],
github='#kakashihatake',
};
becomes
var myInfo = {
fullName: cutName(myArray[0]),
skype: myArray[1],
github: '#kakashihatake'
};
var myArray = ['Isaiah Sias', 'isaiahsias15689'],
github = '#kakashihatake';
function toObject(){
return {
fullName: myArray[0].split(' '),
skype: myArray[1],
github: github
}
}
console.log(toObject());
Maybe I'm not putting in the correct search terms, because I can't find what I want, but I'd like to do something like the below in javascript. I believe the issue could be that I'm trying to dynamically create and assign a value to an array in one call which might not be allowed, or maybe my syntax is just wrong (I come from a PHP background).
var array = [];
array[key][] = value;
return array;
I'm looping through an existing array, and every time I come across a key, I want to add its associated value to a new array under that key. If array[key] doesn't exist yet I want it to be created. If it already exists I want a new value to be added to the existing array[key]. I would like the end result to look something like this:
array = [
[key1] = [value1, value2, value3, value4],
[key2] = [value1, value2, value3, value4],
...
]
It doesn't have to be an array. It can be an object.
Demo code as below:
var array = [];
function pushToArray(key, value){
var subArray = array[key];
if( typeof subArray == "undefined"){
subArray = [];
array[key] = subArray;
}
subArray.push(value);
return subArray;
}
pushToArray("key1", "value11");
pushToArray("key1", "value12");
pushToArray("key2", "value21");
pushToArray("key2", "value22");
console.log(array);
You can use Array to do it, but it looks like Map is what you are looking for? The keys can be stored as Map's key, while for map's object, you can store the Array Objects.
Check out this link Javascripy Map Object
Im using the following code to split array which is working,
I need to pass some value when array
for examle here is split the value to array
var myArr = val.split(/(\s+)/);
and if array in place 2 is empty I need to use the method like following
pass empty array in second arg
var val = process.run(myArr[0], [], options);
if the array place 2 is not empty I need to pass it like following
var val = process.run(myArr[0], [myArr[2]], options);
The second arg is array inside arry with the value of 2
there is nice way to do it instead of if on the method ?
I would create a function, as Dave Newton recommends. I could take the initial val and options as an argument and return the result of process.run:
function runProcess(val, options) {
var myArr = val.split(/(\s+)/);
var argArray = [];
if(myArr[2]) {
argArray.push(myArr[2]);
}
return process.run(myArr[0], argArray, options);
}
Since I don't know what the function exactly does, the name of the function and variables are pretty arbitrary. Feel free to change them to your needs.
If myArr[2] is a flat array and will always be flat, why not...
var val = process.run(myArr[0], [].concat(myArr[2]), options);
my problem is that i have a json-object with and array into here an example.
var object = {
'items':['entry1','entry2']
}
I want to access 'entry2' over a constant string that I receive and shouldn't be changed.
var string = 'items[1]';
The only way I'm solving this problem is over the eval function...
eval('object.'+string);
This returns me entry2.
Is there any other way to achieve this without using eval()?
Like object[string] or object.string
Supposing your string is always the same form, you could extract its parts using a regex :
var m = string.match(/(\w+)\[(\d+)\]/);
var item = object[m[1]][+m[2]];
Explanation :
The regex builds two groups :
(\w+) : a string
\[(\d+)\] : some digits between brackets
and those groups are at index 1 and 2 of the array returned by match.
+something parses the number. It's not strictly needed here as the array accepts a string if it can be converted but I find the code more readable when this conversion is explicited.
On top of dystroy's anwser, you can use this function:
function getValueFromObject(object, key) {
var m = key.match(/(\w+)\[(\d+)\]/);
return object[m[1]][+m[2]];
}
Example:
var object = {
'items':['entry1','entry2']
}
var string = 'items[1]';
var value = getValueFromObject(object, string); //=> "entry2"
First, you can get the array from inside:
var entries = object.items // entries now is ['entry1','entry2']
Then you need to index that to get the second item (in position 1). So you achieve what you want with:
var answer = entries[1] // answer is now 'entry2'
Of course, you can combine this to get both done in one step:
var answer = object.items[1] // answer is now 'entry2'
... I can see this is a contrived example, but please don't call your Objects 'object', or your Strings 'string' :s
try something like this
object.items[1];