admin管理员组文章数量:1310043
I have this challenge, which consists on:
- Writing a function that takes an array of strings as argument
- Then, group the strings in the array by their first letter
- Return an object that contains properties with keys representing first letters
For example:
Should return
groupIt(['hola', 'adios', 'chao', 'hemos', 'accion'])
// Should return
{
a: [ "adios", "accion" ]
c: [ "chao" ]
h: [ "hola", "hemos" ]
}
This is my answer, it returns the expected object, but doesn't pass the test in the page:
function groupIt(arr) {
let groups = {}
let firstChar = arr.map(el=>el[0])
let firstCharFilter = firstChar.filter((el,id)=>{
return firstChar.indexOf(el)===id
})
firstCharFilter.forEach(el=>{
groups[el]=[]
})
firstCharFilter.forEach(char=>{
for(let word of arr) {
if(word[0]==char) {
groups[char].push(word)
}
}
})
return groups
}
const result = groupIt(['hola', 'adios', 'chao', 'hemos', 'accion']);
console.log(result);
I have this challenge, which consists on:
- Writing a function that takes an array of strings as argument
- Then, group the strings in the array by their first letter
- Return an object that contains properties with keys representing first letters
For example:
Should return
groupIt(['hola', 'adios', 'chao', 'hemos', 'accion'])
// Should return
{
a: [ "adios", "accion" ]
c: [ "chao" ]
h: [ "hola", "hemos" ]
}
This is my answer, it returns the expected object, but doesn't pass the test in the page:
function groupIt(arr) {
let groups = {}
let firstChar = arr.map(el=>el[0])
let firstCharFilter = firstChar.filter((el,id)=>{
return firstChar.indexOf(el)===id
})
firstCharFilter.forEach(el=>{
groups[el]=[]
})
firstCharFilter.forEach(char=>{
for(let word of arr) {
if(word[0]==char) {
groups[char].push(word)
}
}
})
return groups
}
const result = groupIt(['hola', 'adios', 'chao', 'hemos', 'accion']);
console.log(result);
Where am I failing at?
Here the test: https://www.jschallenger./javascript-arrays/javascript-group-array-strings-first-letter
Share Improve this question edited Nov 19, 2022 at 22:59 Andy 63.6k13 gold badges71 silver badges98 bronze badges asked Feb 18, 2022 at 18:35 Juan LuisJuan Luis 1331 silver badge8 bronze badges 2- Don't bother to set the keys up first. You'll have to redo that work when figuring out where to insert the words. Instead, for each word: get the key; if that key does not already exist, add the key; add the word. – Ouroborus Commented Feb 18, 2022 at 19:05
- Also, the puzzle author's solution isn't that great. It seems designed to look cool to people with less knowledge but has obvious performance issues. – Ouroborus Commented Feb 18, 2022 at 19:14
8 Answers
Reset to default 3I ran your code as well as the test examples provided by JS challenger. I noticed that they where case sensitive. So although your code works well, if the words begin with upper case it will not pass certain cases. Attached is my version that passed all test examples.
If you add : .toLowerCase to the firstChar, I believe you will pass as well. Happy coding ;)
P.S if the image below does not work please let me know, I am just learning how to contribute to Stack Exchange, thanks.
const groupIt = (array) => {
let resultObj = {};
for (let i =0; i < array.length; i++) {
let currentWord = array[i];
let firstChar = currentWord[0].toLowerCase();
let innerArr = [];
if (resultObj[firstChar] === undefined) {
innerArr.push(currentWord);
resultObj[firstChar] = innerArr
}else {
resultObj[firstChar].push(currentWord)
}
}
return resultObj
}
console.log(groupIt(['hola', 'adios', 'chao', 'hemos', 'accion']))
console.log(groupIt(['Alf', 'Alice', 'Ben'])) // { a: ['Alf', 'Alice'], b: ['Ben']}
console.log(groupIt(['Ant', 'Bear', 'Bird'])) // { a: ['Ant'], b: ['Bear', 'Bird']}
console.log(groupIt(['Berlin', 'Paris', 'Prague'])) // { b: ['Berlin'], p: ['Paris', 'Prague']}
The site doesn't like .reduce
, but here's one way:
const r1 = groupIt(['hola', 'adios', 'chao', 'hemos', 'accion'])
console.log(r1)
// Should return
// {
// a: ["adios", "accion"]
// c: ["chao"]
// h: ["hola", "hemos"]
// }
function groupIt(arr) {
return arr.reduce((store, word) => {
const letter = word.charAt(0)
const keyStore = (
store[letter] || // Does it exist in the object?
(store[letter] = []) // If not, create it as an empty array
);
keyStore.push(word)
return store
}, {})
}
Case sensitive is the reason. Pop a toLowerCase in after the charAt(0).
Here's my example:
https://stackblitz./edit/node-tebpdp?file=ArrayStringsFirstLetter.js
Link to screenshot!
You could take Object.groupBy
with a callback for the grouping constraint.
const
groupIt = array => Object.groupBy(array, ([c]) => c.toLowerCase());
console.log(groupIt(['hola', 'adios', 'chao', 'hemos', 'accion']));
.as-console-wrapper { max-height: 100% !important; top: 0; }
You code is correct, the only wrong part is that you are not lowercasing the first letter, here is your code with additional lowercasing of the first letter, so it passes the test:
function groupIt(arr) {
let groups = {}
let firstChar = arr.map(el=>el[0])
let firstCharFilter = firstChar.filter((el,id)=>{
return firstChar.indexOf(el)===id
})
firstCharFilter.forEach(el=>{
groups[el.toLowerCase()]=[]
})
firstCharFilter.forEach(char=>{
for(let word of arr) {
if(word[0]==char) {
groups[char.toLowerCase()].push(word)
}
}
})
return groups;
}
const groupIt = (arr) => {
return arr.reduce((acc, cur) => {
const firstLetter = cur[0].toLowerCase();
return { ...acc, [firstLetter]: [...(acc[firstLetter] || []), cur] };
}, {});
};
function groupIt(arr) {
var obj = {};
arr.forEach(e => obj[e[0].toLowerCase()] = arr.filter(ele => ele[0].toLowerCase() == e[0].toLowerCase()));
return obj;
}
console.log(groupIt(['Alf', 'Alice', 'Ben'])); //{ a: [ 'Alf', 'Alice' ], b: [ 'Ben' ] }
console.log(groupIt(['Ant', 'Bear', 'Bird'])); // { a: [ 'Ant' ], b: [ 'Bear', 'Bird' ] }
console.log(groupIt(['Berlin', 'Paris', 'Prague'])); // { b: [ 'Berlin' ], p: [ 'Paris', 'Prague' ] }
Here's my example:
function myFunction(arr){
let count = {}
arr.forEach((e, i)=>{
count[e.charAt(0)] = [...count[e.charAt(0)] || [],e]
})
return count
}
myFunction(['hola', 'adios', 'chao', 'hemos', 'accion'])
本文标签: javascriptGroup array of strings by first letterStack Overflow
版权声明:本文标题:javascript - Group array of strings by first letter - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741834300a2400121.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论