Filter array by string length in javascript

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"));
4 (they) --> 'they' length is 4 etc.
3 (say)
11 (programming)
2 (is)
3 (fun)
3 (but)
2 (it)
2 (is)
3 (not)

What I want to return is the word with the same length as below, but I don’t know how to go about this:

4 (they)
3 (say, fun, but, not)
11 programming
2 (is, it, is)

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.

That would create an array like this:

var filteredWords = [
  [],
  ["is", "it", "is"],
  ["say", "fun", "but", "not"],
  ["they"],
  [],
  [],
  [],
  [],
  [],
  [],
  ["programming"],
];

You will see the array filteredWords can now be accessed and you have an array containing all 3 letter long words by doing filteredWords[2].

Then add a for loop similar to this:

for (var i = 0; i < filteredWords.length; i++) {
  if (filteredWords[i].length) {
    console.log(i + 1 + filteredWords[i].join(", ");
  }
}

My solution is not perfect, but that’s how I would go about it :slight_smile:

1 Like

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.

1 Like

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 :stuck_out_tongue:

1 Like

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

{ '2': [ 'is', 'it', 'is' ],
  '3': [ 'say', 'fun', 'but', 'not' ],
  '4': [ 'they' ],
  '11': [ 'programming' ] }
1 Like

Thanks for your time, this works :+1:. I will also try to implement other ways in order to learn.

You can in fact use integers as keys - no need to come up with “twelve” or anything :wink:

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.

2 Likes

Oh, I didn’t know!
Thank you for telling me :slight_smile:
I thought keys were the same as variable names - can’t start with a number. But I was wrong :stuck_out_tongue:

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.