const test = (strs: string[]) => Object.values( strs.reduce((acc, el) => { const key = el.split("").sort().join(""); acc[key] = [...(acc[key] || []), el].sort(); return acc; }, {} as Record) ).sort((a, b) => a.length - b.length); // ======================== console.log(test(["eat", "tea", "tan", "ate", "nat", "bat"])); console.log(test([""])); console.log(test(["a"]));