I want to create an array 2D that contains each alphabet. The problem is, I am just able to create an array 2D that contains all alphabet. I do the following.
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' ]));
but the output is
[ [ 'bear', 'chicken', 'cat', 'dolphin', 'tiger' ] ]
[ [ 'ant', 'bird', 'dog', 'elephant', 'fish', 'flamingo', 'horse' ] ]
instead of
[ ['bear'], ['chicken', 'cat], ['dolphin'], ['tiger'] ]
[ ['ant'], ['bird'], ['dog'], ['elephant'], ['fish', 'flamingo'], ['horse']]
i have tried to make an array temp first after alphabet looping, and then push the animal's name to it, but it's too manual, draining time and there will be an empty array if there's no such character. I want to do it by looping, but i have no idea how to do the loop.
function groupAnimals(animals) {
var sort = []
var alphabet = 'abcdefghijklmnopqrstuvwxyz'
for(var i = 0; i < alphabet.length; i++){
var A = []
var B = []
var C = []
var D = []
var E = []
var F = []
var T = []
for(var j = 0; j < animals.length; j++){
if(animals[j][0] == 'a'){
A.push(animals[j])
} else if(animals[j][0] == 'b'){
B.push(animals[j])
} else if(animals[j][0] == 'c'){
C.push(animals[j])
} else if(animals[j][0] == 'd'){
D.push(animals[j])
} else if(animals[j][0] == 'e'){
E.push(animals[j])
} else if(animals[j][0] == 'f'){
F.push(animals[j])
} else if(animals[j][0] == 't'){
T.push(animals[j])
}
}
}
sort.push(A)
sort.push(B)
sort.push(C)
sort.push(D)
sort.push(E)
sort.push(F)
sort.push(T)
return sort
}
and the result is
[ [],
[ 'bear' ],
[ 'chicken', 'cat' ],
[ 'dolphin' ],
[],
[],
[ 'tiger' ] ]
[ [ 'ant' ],
[ 'bird' ],
[],
[ 'dog' ],
[ 'elephant' ],
[ 'fish', 'flamingo' ],
[] ]
use array and loops are preferable