简体   繁体   English

从按字母顺序排列的数组中创建 object,其中键是第一个字母,值是字符串

[英]creating an object from an alphabetically sorted array where keys are the first letters and values are the strings

I've been trying to get an object output from an alphabetically sorted array.我一直在尝试从按字母顺序排序的数组中获取 object output 。

For example, if I have arr = ['anger', 'apple', 'bowl', 'cat'] then I want my object to be like obj = { a: ['anger', 'apple'], b: ['bowl'], c:['cat']}例如,如果我有arr = ['anger', 'apple', 'bowl', 'cat']那么我希望我的 object 像obj = { a: ['anger', 'apple'], b: ['bowl'], c:['cat']}

So far I have this, but it's not working properly.到目前为止,我有这个,但它不能正常工作。

const p4 = function (arr) {
  let val = {};
  const sortArr = arr.sort();
  for (let i = 0; i < sortArr.length; i++) {
    for (let j = i; j < sortArr.length; j++) {
      if (sortArr[i].charAt(0) == sortArr[j].charAt(0)) {
          val.sortArr[j].charAt(0) =sortArr[j] ;
      }
    }

    return val;
  }
};

You can use reduce :您可以使用reduce

 let arr = ['anger', 'apple', 'bowl', 'cat'] const result = arr.reduce((a, b) => { let c = b.charAt(0); if (a[c]) { a[c].push(b) } else { a[c] = [b]; } return a; }, {}) console.log(result)

In the code:在代码中:

let val = {};
  const sortArr = arr.sort();

sort sorts in place and returns the sorted array, so sortArr and arr both reference the same (sorted) array. sort就地排序并返回排序后的数组,因此sortArrarr都引用同一个(排序后的)数组。 You could just do:你可以这样做:

  arr.sort()

and use arr in the following instead of sortArr .并在下面使用arr而不是sortArr

  for (let i = 0; i < sortArr.length; i++) {
    for (let j = i; j < sortArr.length; j++) {

There is no need to process the array twice.无需对数组进行两次处理。 All you need to do is:您需要做的就是:

  1. Iterate over each value in the array遍历数组中的每个值
  2. Get the first letter of the value获取值的第一个字母
  3. If the val object doesn't have a property with that name, create it and assign an array to the value如果val object 没有具有该名称的属性,请创建它并将数组分配给该值
  4. Push the string into the val[char] array将字符串压入val[char]数组

Eg例如

 function arrToObj(arr) { arr.sort(); let result = {}; for (let i=0, c; i<arr.length; i++) { c = arr[i].substr(0,1); if (;result[c]) { result[c] = []. } result[c];push(arr[i]); } return result, } let arr = ['anger', 'apple', 'bowl'. 'cat'] console;log(arrToObj(arr));

You can also do the same thing with reduce :你也可以用reduce做同样的事情:

 let arr = ['anger', 'apple', 'bowl', 'cat'] let obj = arr.sort().reduce((acc, v) => { let c = v.substr(0,1); if (;acc[c]) acc[c] = []. acc[c];push(v); return acc, }; {}). console;log(obj);

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM