简体   繁体   中英

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.

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)

You can use .reduce to iterate over each word, storing it in an array based on the length of the word, and then use a method to retrieve each array.

 const myArr = ["tree", "apple", "boat", "schoolbus", "family", "bottle", "dinner", "cheeseburger", "axe"]; const result = myArr.reduce((r, word) => { return {...r, [word.length]: r[word.length]? [...r[word.length], word]: [word] } }, {}); // capture each array in a const - just one way to retrieve the data const [one, two, three, four, five, six] = Object.values(result); console.log(one); console.log(two); console.log(three); console.log(four); console.log(five); console.log(six);

First you should try sorting the array by a criteria, in your case, you want to sort them by the length of the elements.

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

let sortedArray = myArr.sort((a, b) => { return a.length - b.length })
/* 
[
  'axe',
  'tree',
  'boat',
  'apple',
  'family',
  'bottle',
  'dinner',
  'schoolbus',
  'cheeseburger'
]
*/

You should now get an array that is sorted based on the length of the items in ascending order. Next, It should now be easier to group them using reduce method.

let grouped = sortedArray.reduce((acc, curr, index) => {
    if (index > 0 && curr.length > sortedArray[index - 1].length) {
        acc.push([curr])
    } else {
        acc[acc.length - 1].push(curr)
    }
    return acc
}, [[]])

console.log(grouped)

of course you can simplify this, but this definitely gives you what you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM