我想创建一个包含每个字母的2D数组。问题是,我只能创建一个包含所有字母的2D数组。 我执行以下操作。
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' ]));
但输出是
[ [ 'bear', 'chicken', 'cat', 'dolphin', 'tiger' ] ]
[ [ 'ant', 'bird', 'dog', 'elephant', 'fish', 'flamingo', 'horse' ] ]
代替
[ ['bear'], ['chicken', 'cat], ['dolphin'], ['tiger'] ]
[ ['ant'], ['bird'], ['dog'], ['elephant'], ['fish', 'flamingo'], ['horse']]
我尝试过在字母表循环后先创建一个数组临时文件,然后再将动物的名字推给它,但这太手工了,浪费时间,如果没有这样的字符,就会有一个空数组。我想通过循环来做到这一点,但我不知道如何进行循环。
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
}
结果是
[ [],
[ 'bear' ],
[ 'chicken', 'cat' ],
[ 'dolphin' ],
[],
[],
[ 'tiger' ] ]
[ [ 'ant' ],
[ 'bird' ],
[],
[ 'dog' ],
[ 'elephant' ],
[ 'fish', 'flamingo' ],
[] ]
最好使用数组和循环
答案 0 :(得分:3)
简化为数组对象,其中的键是值数组中单词的第一个字母,然后使用Object.values
将其转换回数组数组:
const groupAnimals = (animals) => {
const sorted = animals.slice().sort();
const groupedObj = sorted.reduce((a, word) => {
const key = word[0];
if (!a[key]) {
a[key] = [];
}
a[key].push(word);
return a;
}, {});
return Object.values(groupedObj);
};
console.log(groupAnimals(['bear', 'chicken', 'dolphin', 'cat', 'tiger']));
console.log(groupAnimals(['elephant', 'fish', 'horse', 'bird', 'flamingo', 'dog', 'ant']));
上面的方法可以工作,但是如果您担心规范不能正式保证属性顺序,则可以随后对数组进行排序:
const groupAnimals = (animals) => {
const groupedObj = animals.reduce((a, word) => {
const key = word[0];
if (!a[key]) {
a[key] = [];
}
a[key].push(word);
return a;
}, {});
return Object.values(groupedObj)
.sort((a, b) => a[0][0].localeCompare(b[0][0]));
};
console.log(groupAnimals(['bear', 'chicken', 'dolphin', 'cat', 'tiger']));
console.log(groupAnimals(['elephant', 'fish', 'horse', 'bird', 'flamingo', 'dog', 'ant']));
答案 1 :(得分:0)
压榨SomePerformance的答案,并先将所有内容更改为小写,以防影响排序。
function groupStrings(strings) {
return Object.values(strings.sort().reduce((a, str) => {
const s = str.toLowerCase();
const f = s[0];
a[f] = a[f] ? [...a[f], s] : [s];
return a;
}, {}));
}
console.log(groupStrings(['bear', 'chicken', 'dolphin', 'cat', 'tiger']));
console.log(groupStrings(['chevrolet', 'buick', 'dodge', 'bmw', 'mercedes', 'jaguar', 'landrover', 'audi', 'volkswagen', 'cadilac', 'ford', 'toyota', 'tesla']));
这里有几种处理数组和仅用于循环的方法。注释中有解释:
function groupStrings(strings) {
// first sort the array
var sortedStrings = strings.slice().sort();
// create the start of the 2d array with the first word
var twoDArray = [[sortedStrings[0]]];
for (var i = 1; i < sortedStrings.length; i++) {
// get the last child array in the 2d array
var currentArray = twoDArray[twoDArray.length-1];
// if the first letter of the current string is equal to the first letter of a string in the current child array,
// add the current string to the current child array
if (sortedStrings[i][0] === currentArray[0][0]) {
currentArray.push(sortedStrings[i]);
currentArray = currentArray.sort();
// otherwise create a new child array with the current string
} else {
twoDArray.push([sortedStrings[i]])
}
}
return twoDArray;
};
console.log(groupStrings(['bear', 'chicken', 'dolphin', 'cat', 'tiger']));
console.log(groupStrings(['chevrolet', 'buick', 'dodge', 'bmw', 'mercedes', 'jaguar', 'landrover', 'audi', 'volkswagen', 'cadilac', 'ford', 'toyota', 'tesla']));
function groupStrings(strings) {
var alphabet = 'abcdefghijklmnopqrstuvwxyz';
var twoDArray = [];
for (var i = 0; i < alphabet.length; i++) {
// create a temporary array for all words starting with the current letter
var letterArray = [];
for (var j = 0; j < strings.length; j++) {
// if the first letter of the current string is equal to the current letter,
// add it to the letter array
if (strings[j][0] === alphabet[i]) {
letterArray.push(strings[j]);
}
}
// if any strings were added, add the letter array to the 2d array
if (letterArray.length) {
twoDArray.push(letterArray);
}
}
return twoDArray;
};
console.log(groupStrings(['bear', 'chicken', 'dolphin', 'cat', 'tiger']));
console.log(groupStrings(['chevrolet', 'buick', 'dodge', 'bmw', 'mercedes', 'jaguar', 'landrover', 'audi', 'volkswagen', 'cadilac', 'ford', 'toyota', 'tesla']));