简体   繁体   English

按第一个字母对字符串数组进行分组

[英]Group array of strings by first letter

I have this challenge, which consists on:我有这个挑战,其中包括:

  • Writing a function that takes an array of strings as argument编写一个将字符串数组作为参数的 function
  • Then, group the strings in the array by their first letter然后,将数组中的字符串按第一个字母分组
  • Return an object that contains properties with keys representing first letters返回一个 object,其中包含带有表示第一个字母的键的属性

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:这是我的答案,它返回预期的 object,但没有通过页面中的测试:

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
}

groupIt(['hola', 'adios', 'chao', 'hemos', 'accion'])

Where am I failing at?我哪里失败了?

Here the test: https://www.jschallenger.com/javascript-arrays/javascript-group-array-strings-first-letter这里是测试: https://www.jschallenger.com/javascript-arrays/javascript-group-array-strings-first-letter

I ran your code as well as the test examples provided by JS challenger.我运行了您的代码以及 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.如果您将 : .toLowerCase 添加到 firstChar,我相信您也会通过。 Happy coding ;)快乐编码;)

PS if the image below does not work please let me know, I am just learning how to contribute to Stack Exchange, thanks. PS 如果下面的图片不起作用,请告诉我,我正在学习如何为 Stack Exchange 做出贡献,谢谢。

 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:该网站不喜欢.reduce ,但这是一种方法:

 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).在 charAt(0) 之后弹出一个 toLowerCase。

Here's my example:这是我的例子:

https://stackblitz.com/edit/node-tebpdp?file=ArrayStringsFirstLetter.js https://stackblitz.com/edit/node-tebpdp?file=ArrayStringsFirstLetter.js

Link to screenshot!链接到截图!

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' ] }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 按属性首字母分组对象数组 - group array of objects by property first letter Angular 2组对象的第一个字母数组 - Angular 2 Group array of objects by first letter JS:循环遍历字符串,找到第一个字母,输出为字母组锚到关联的字符串? - JS: loop through strings, find first letter, output as letter group anchor to associated string(s)? 给定一个字符串数组,将每个字符串转换为: 如果第一个字母大写则大写 如果第一个字母小写则小写 - Given an array of strings, convert each string into: uppercase if first letter is capital lower case if first letter is small 为什么字符串数组中的第一个字母不转换为大写? - Why first letter in array of strings don't convert to upper case? 仅样式化 React Native 中字符串数组的第一个字母 - Styling only first letter from an array of strings in React Native 按第一个字母对数组进行分组 - 使用 groupBy 方法 (Lodash) - Group an array by its first letter - using groupBy method (Lodash) 如何按首字母对列表进行分组? - How to group a list by first letter? 如何编写一个 function,它将字符串数组作为参数并打印出每个元素的第一个字母(每行一个) - How to write a function that takes an Array of strings as an argument and prints the first letter of each element out (one per line) For 循环检查数组中的第一个字母 - For loop to check the first letter in an array
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM