Skip to content
Advertisement

How to split an array of strings into subarrays based on the length of the words

I’m looking for a way to split an array of strings into new arrays(?) based on the length of the words.

const myArr = ["tree", "apple", "boat", "schoolbus", "family", "bottle", "dinner", "cheeseburger", "axe"];

// Splitted result
["axe"], ["tree", "boat"], ["apple"], ["family", "bottle", "dinner"], ["schoolbus"], ["cheeseburger"];

I don’t know if and how I have to split this into new arrays. I will have to loop (foreach/map) through the newly created arrays but also be able to know what the length of the words is.

Advertisement

Answer

Unless you know the number of unique lengths beforehand, you’re better off using an object.

const res = {};
myArr.forEach((s) => {
  if (!res[s.length]) res[s.length] = [s];
  else res[s.length].push(s);
});

If you want the result as an array, you can use Object.values(res)

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement