Hi!
I want to return a string with the same length. The below code returns the length of each word.
function letterCounter(str) {
let count = 1;
let wordSplit = str.split(" ")
console.log(wordSplit)
let filtered = wordSplit.filter( function( element ) {
console.log(element.length + " " + element)
});
return filtered;
}
console.log(letterCounter("they say programming is fun but it is not"));
Hey!
If I were you, I’d create an array of arrays. First, find the length of the longest word. This will be how many sub-arrays you will have.
Now go through every word from your input and determine the length. Now add it to the proper subarray (ie. if the wordlength is 2, add it to the 2nd subarray and if the wordlength is 11, you would add it to the 11th subarray). Remember array indexes start with 0.
An array of arrays does work, though it runs into the problem of having some empty space.
Alternativly you could create a dictionairy with keys being the number of letters and values being an array of the words.
Both work, but an array of arrays is easier to implement and I while I did mention it, I don’t think a dictionairy offers any benefits in this situation. But they are very useful data-structures so no harm in knowing them.
I thought of that too - Only add a key-value pair when there is an instance of that wordlength. But I could not come up with a way to easily implement a key called “one” and which would work for all wordlengths.
Consider a situation where words would be up to 12 letters long. You’d have to create a dictionary/object that would have the key name “twelve” and easily be able to access the key “twelve” when you want to print it again. Had it been python it would have been possible to loop through a dictionary, but since it’s JavaScript, I don’t see an easy solution to that?
Though I am a “newbie” so I might not have the best solution or most knowledge
hi, this is how i would do it, idk if it fits with how you want the process to go:
let str="they say programming is fun but it is not"
str=str.split(' ')
let obj={}
str.forEach(word=>{
let l=word.length
if (obj[l]) obj[l].push(word)
else obj[l]=[word]
})
let me know if you need additional narrative for the code
PS: it returns an object with number keys(1,2,3,10 and whatever word length it encounters in the string) and each key is assigned an array containing every word with corresponding length
You can in fact use integers as keys - no need to come up with “twelve” or anything
For an output you could either use Object.keys(dict) which creates an array containing all keys in a semi-random order - OR keep track of the longest word and then create a for-loop (1 to maxlength) with an if-statement that creates an output whenever a number is a key - as Sylvant showed that’s also quite easy.