I'm trying to create a 2D array that groups animals by their first letter of the alphabet. However, the output is not what I expected. I want each letter to have its own sub-array with corresponding animal names. Here's the code I tried:
function groupAnimals(animals) {
var sort = [];
var alphabet = 'abcdefghijklmnopqrstuvwxyz';
var temp = [];
for(var i = 0; i < alphabet.length; i++){
for(var j = 0; j < animals.length; j++){
if(animals[j][0] == alphabet[i]){
temp.push(animals[j]);
}
}
}
sort.push(temp);
return sort;
}
console.log(groupAnimals(['bear', 'chicken', 'dolphin', 'cat', 'tiger']));
console.log(groupAnimals(['elephant', 'fish', 'horse', 'bird', 'flamingo', 'dog', 'ant']));
However, the output does not match my expected format. I want to achieve the following instead:
[ ['bear'], ['chicken', 'cat'], ['dolphin'], ['tiger'] ]
[ ['ant'], ['bird'], ['dog'], ['elephant'], ['fish', 'flamingo'], ['horse'] ]
My attempt to manually create sub-arrays based on the first letter of each animal proved to be inefficient and produced unexpected results. I want to achieve this using arrays and loops, but I'm struggling to figure out how to do it. Any suggestions or solutions would be greatly appreciated.
function groupAnimals(animals) {
var sort = [];
var alphabet = 'abcdefghijklmnopqrstuvwxyz';
for(var i = 0; i < alphabet.length; i++){
var tempArr = [];
for(var j = 0; j < animals.length; j++){
if(animals[j][0] == alphabet[i]){
tempArr.push(animals[j]);
}
}
sort.push(tempArr);
}
return sort;
}
When I tried the above code, the output was:
[ ['bear'], ['chicken', 'cat'], ['dolphin'], ['tiger'], [], [], []]
[ ['ant'], ['bird'], [], ['dog'], ['elephant'], ['fish', 'flamingo'], ['horse']]
I'm looking for a more efficient solution using arrays and loops to achieve the desired output.